Variables to TXT file
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 17 de Mayo de 2017
Editada: MathWorks Support Team
el 5 de Mzo. de 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?
Respuesta aceptada
MathWorks Support Team
el 5 de Mzo. de 2021
Editada: MathWorks Support Team
el 5 de Mzo. de 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 comentario
Stephen23
el 2 de Jun. de 2017
Editada: Stephen23
el 2 de Jun. de 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);
Más respuestas (0)
Ver también
Categorías
Más información sobre Downloads en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!