How to generate m code for a variable

3 views (last 30 days)
Hui Li
Hui Li on 5 Aug 2022
Commented: Walter Roberson on 8 Aug 2022
I'd like to write a script to generate m code for variable in the work space.
For example I have a variable aa in the workspace.
I want to auto create a script called "parameter.m" which contains the following text:
The actual job I need to do is more complicated than this aa example. My workspace variable will be larger in dimension and I'll have 4-5 different variables to generate. Is there a way to do achieve this?

Answers (1)

Walter Roberson
Walter Roberson on 5 Aug 2022
If the variable is double precision and is at most 2 dimensions, then you can use mat2str to construct the right hand side
aa = magic(5)
aa = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
ans = '[17 24 1 8 15;23 5 7 14 16;4 6 13 20 22;10 12 19 21 3;11 18 25 2 9]'
If it is numeric and at most 2 dimensions but is a different data type, then you can use mat2str() but you would have to insert the type conversion yourself.
If it is numeric but more than 2 dimensions, then unfortunately there is no Mathworks routine that will automatically build the required cat() calls to put together 2d slices in an appropriate way.
For numeric with more than 2 dimension, or for structures or cell arrays, you might want to consider jsonencode
bbb = reshape(magic(6), 2, 3, []);
ans = '[[[35,1,6,26,19,24],[31,9,2,22,27,20],[30,5,34,12,14,16]],[[3,32,7,21,23,25],[8,28,33,17,10,15],[4,36,29,13,18,11]]]'
The string produced is not MATLAB code itself, but it is something you could wrap in a jsondecode call.
Is the point to automatically generate MATLAB-language code, or is the point to generate something that, when executed, gives you back a replica of the original?
Walter Roberson
Walter Roberson on 8 Aug 2022
The question becomes whether what is generated needs to be distinctly MATLAB code, human readable as MATLAB code (whether for review purposes or to allow easy editing) -- or whether it just needs to be something that when executed gives back a clone of the original data. And, of course, which kinds of variables this will be limited to.
For example if it is applied to a figure, then does it need to generate all of the graphics calls needed to recreate the figure? And if so, then if a figure with that number already exists then should it operate on that figure or should it create a new figure.
Recreating something like an open TCP connection or a parpool data queue might not be feasible.

Sign in to comment.




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!