Read number from a string from multiple files
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
carola forlini
le 13 Juin 2023
Commenté : carola forlini
le 13 Juin 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 commentaire
Stephen23
le 13 Juin 2023
Modifié(e) : Stephen23
le 13 Juin 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.
Réponse acceptée
Stephen23
le 13 Juin 2023
Modifié(e) : Stephen23
le 13 Juin 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.:
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Filename Construction dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!