How to generate m code for a variable
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
0 Commenti
Risposte (1)
Walter Roberson
il 5 Ago 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)
mat2str(aa)
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, []);
jsonencode(bbb)
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?
2 Commenti
Walter Roberson
il 8 Ago 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.
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!