Reputation: 35321
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.
Upvotes: 5
Views: 912
Reputation: 21
As Sam Roberts commented, matlab.io.saveVariablesToScript
is now the ultimate method to convert any datatype to a script. This method was introduced in 2014a and works for struct
, cell
, and all primitive datatypes.
chappjc's method is also correct, but it uses a MATLAB GUI frontend to the saveVariablesToScript
method.
Upvotes: 1
Reputation: 13758
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.
Upvotes: 4
Reputation: 30579
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.
Upvotes: 2