Variables to TXT file

2 views (last 30 days)
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? 

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 5 Mar 2021
Edited: MathWorks Support Team on 5 Mar 2021
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 Comment
Stephen23
Stephen23 on 2 Jun 2017
Edited: Stephen23 on 2 Jun 2017
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);

Sign in to comment.

More Answers (0)

Categories

Find more on Downloads in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!