Is there a way to dump a MATLAB variable as the source code for the corresponding literal initializer? IOW, I'm looking for some function x
such that, for example:
>> A = zeros(2);
>> x(A)
ans =
[0 0; 0 0]
>> class(x(A))
ans =
char
Is there such a function, or an easy way to achieve the same effect? (I realize that literal initializers may not exist for some MATLAB items; for such items the problem is intrinsically unsolvable.)
I am aware of the fact that MATLAB offers many ways to save data to files, but none of the ways I've found produce MATLAB source code, which is what I'm after.
To save all workspace variables to a MAT-file, on the Home tab, in the Variable section, click Save Workspace. To save a subset of your workspace variables to a MAT-file, select the variables in the Workspace browser, right-click, and then select Save As.
To write a text file with columns of data that have variable names, use the “writetable” function. First, create the data to write, put it in a table with variable names, and then write the data to text file.
To create a variable enter the name of the variable in the command window, followed by an = operator, and then assign it some values.
MATLAB displays the variables in the nested get_date function, and the variables in all functions that contain the nested function, grouped by function workspace.
For simple numeric values (and also char arrays), the mat2str
function does what you're looking for.
For example, (from the MATLAB documentation):
Consider the matrix
x = [3.85 2.91; 7.74 8.99] x = 3.8500 2.9100 7.7400 8.9900
The statement
A = mat2str(x)
produces
A = [3.85 2.91;7.74 8.99]
where
A
is a string of 21 characters, including the square brackets, spaces, and a semicolon.
Further, passing the string 'class'
as the second argument ensure that the answer will be case to the correct numeric type.
See the MATLAB documentation for mat2str
, or run
doc mat2str
in MATLAB, for more information.
I know you are looking for a function that can do this, rather than an interactive procedure, but for anyone else who wants to do this manually...
The MATLAB variable editor/viewer has built-in code generation functionality. Open the variable in the editor, click the save icon, and choose MATLAB Script (*.m) file type (default is .mat):
The resulting MatrixCode.m:
% -------------------------------------------------------------------
% Generated by MATLAB on 3-Mar-2014 17:35:49
% MATLAB version: 8.3.0.73043 (R2014a)
% -------------------------------------------------------------------
M = ...
[16 2 3 13;
5 11 10 8;
9 7 6 12;
4 14 15 1];
Maybe someone with Java and reverse engineering skills can figure out how to call this GUI operation from the command line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With