How to generate m code for a variable
14 次查看(过去 30 天)
显示 更早的评论
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1089400/image.png)
I want to auto create a script called "parameter.m" which contains the following text:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1089405/image.png)
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 个评论
回答(1 个)
Walter Roberson
2022-8-5
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 个评论
Walter Roberson
2022-8-8
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!