Read number from a string from multiple files

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2023-6-13
编辑:Stephen23 2023-6-13
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.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2023-6-13
编辑:Stephen23 2023-6-13
"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.:

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Filename Construction 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by