Duplicating "Save Workspace" button with command.

I'm trying to duplicate pushing the "Save Workspace" button, setting the "Files of Type" to ".m" file. The result of this is a ".m" file that looks like:
A1 = 2.5;
B1 = 27.31;
X4 = [0.4719; 0.0013; 2.5; 3.162-5; 9.900; 2.5];
In addition a .mat file for the items that couldn't be coverted to clean ascii I guess, but I don't care about the .mat file, I only care about the .m file.
I have tried all options that seem to be documentd in the "save" function like "save('outcmd.m','-ascii','-double')", including "-ascii", "-tabs", none of them produce the same output. I'm guessing "save" maybe isn't the correct function, or there is a hidden argument.
Can you provide the correct command to duplicate the output above?

 采纳的回答

matlab.io.saveVariablesToScript('filename.m')

4 个评论

Thank you. That worked perfectly.
Maybe this should be added to the "see also" section of the "save" function. It is very hard to find. Even typing "save variables" into the help center doesn't return this function, you have to type the full name to get it (To any devs or documentors listening...).
In general it is discouraged to store data in mfiles:
  • numeric data are likely to lose precision, whereas data file formats can store the complete precision.
  • loading data from data files explicitly into variables allows the MATLAB JIT engine to optimize memory allocation for that data.
  • data file formats allow only some of the data to be loaded, e.g. format string to specifiy to read of only part of a matrix, or use load to import only a subset of variables from a .mat file.
  • because mfiles are continuously scanned and parsed automatically by MATLAB and invalid mfile format can cause unexpected MATLAB behavior: https://www.mathworks.com/matlabcentral/answers/423543-why-does-this-data-file-cause-matlab-to-lock-up
Summary: data should be stored in data files, which is what the documentation encourages.
That is good info to keep in mind for the future. However in my case I'm trying to get the data out of Matlab into Python and for reasons wanted a readable file format. Much of this stems from my frustration trying to figure out the "Matlab way" to do simple things, for example, to compare 2 variables from 2 .mat files. I'm an expert programmer, but a Matlab novice, and I find it difficult, often spending hours, often finding some convoluted code contributed by users, just to perform somthing as simple as that comparison. So I give up, and move the data out and use another system. I do appreciate all the help available here on the "Answers" forum, but the answers often seem to be far more complex than should be required. Thanks.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息

产品

版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by