Variables to TXT file

1 次查看(过去 30 天)
I have variables in a MAT file that I would like to save the names of and put in a TXT file. Is there a way that I can do this programmatically? 

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2021-3-5
You may achieve this using "fprintf", as shown in the following code snippet:
clear
%Load MAT File
S = whos();
C = {S.name};
fid = fopen('variable_names.txt','wt');
fprintf(fid,'%s\n',C{:});
fclose(fid);
You may find more information on "fprintf" in the documentation at the following link:
  1 个评论
Stephen23
Stephen23 2017-6-2
编辑:Stephen23 2017-6-2
This is unusually inefficient code coming from TMW. For example, why call whos twice?:
numvars = length(whos);
w = whos;
when surely once is enough:
w = whos;
numvars = numel(w);
Although constructing the cell array using preallocation of a cell array is not required anyway, because a comma-separated list is much simpler and requires only one line (and so numvars is not required):
X = {w.name};
versus the code in the answer:
X=cell(1,numvars);
[X{:}]=w.name;
Using fprintf in a loop? Ouch! Much easier to use a comma-separated list again, no loop is required:
fprintf(fid,'%s\n',X{:})
So finally my take on this would be just five simple lines:
S = whos();
C = {S.name};
fid = fopen('variable_names.txt','wt');
fprintf(fid,'%s\n',C{:});
fclose(fid);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by