Read number from a string from multiple files

1 visualización (últimos 30 días)
carola forlini
carola forlini el 13 de Jun. de 2023
Comentada: carola forlini el 13 de Jun. de 2023
Hello,
I have multiples output files from a numerical simulations called eta_0000d, where d is a number going from 0 to #of iteration.
I am trying to make a code which will put all the eta_0000d files into a structure for further analysis.
So far this is the code I made:
fdir = './output/';
%Load eta output
n = 400
S = [];
for i = 1:n
if i<=9
filename = sprintf('eta_0000%d',i);
elseif i<100
filename = sprintf('eta_000%d',i);
else
filename = sprintf('eta_00%d',i);
end
S(i).eta = load([fdir filename]);
end
In the code I manually put the number n (n=400) equivalent to the total output eta files that I see in the output folder. Is there a way to modify my code such that it counts how many eta files there are in the output folder without having to manually input this value?
Thank you
  1 comentario
Stephen23
Stephen23 el 13 de Jun. de 2023
Editada: Stephen23 el 13 de Jun. de 2023
Note that you should replace this:
if i<=9
filename = sprintf('eta_0000%d',i);
elseif i<100
filename = sprintf('eta_000%d',i);
else
filename = sprintf('eta_00%d',i);
end
with one SPRINTF call, by specifying the fieldwidth and leading zero:
filename = sprintf('eta_%05d',i);
% ^ leading zeros
% ^ field width
And also replace the text concatenation with FULLFILE.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 13 de Jun. de 2023
Editada: Stephen23 el 13 de Jun. de 2023
"is there a way to modify my code such that it counts how many eta files there are in the output folder without having to manually input this value?"
Of course, just use DIR:
For example:
P = './output';
S = dir(fullfile(P,'eta_*'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).eta = load(F);
end
If the files are actually text files, then you should use a more appropriate function, e.g.:

Más respuestas (0)

Categorías

Más información sobre Data Import and Analysis en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by