Variables to TXT file
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 17 Mai 2017
Modifié(e) : MathWorks Support Team
le 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?
Réponse acceptée
MathWorks Support Team
le 5 Mar 2021
Modifié(e) : MathWorks Support Team
le 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 commentaire
Stephen23
le 2 Juin 2017
Modifié(e) : Stephen23
le 2 Juin 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);
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Workspace Variables and MAT Files dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!