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
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
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 Center 및 File Exchange에서 Filename Construction에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!