Variables to TXT file
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
MathWorks Support Team
il 17 Mag 2017
Modificato: MathWorks Support Team
il 5 Mar 2021
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?
Risposta accettata
MathWorks Support Team
il 5 Mar 2021
Modificato: MathWorks Support Team
il 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 Commento
Stephen23
il 2 Giu 2017
Modificato: Stephen23
il 2 Giu 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);
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Workspace Variables and MAT Files in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!