Checking index numbers against non-contiguous file names

조회 수: 1 (최근 30일)
Natalie Cannon
Natalie Cannon 2020년 9월 28일
댓글: Natalie Cannon 2020년 9월 28일
I am currently trying to upgrade a section of code by having the code figure out how many files there are instead of having the user enter the number.
What I have so far is:
filenumberfinal=dir( '*FM*.txt');
out=size(filenumberfinal,1);
This works great if all of the files are contiguous, but that might not always be the case.
Is there a way to check that each index number has a matching file to it?
For reference files are named as follows:
###_FM##_HF_0221
where # is a number

채택된 답변

Cam Salzberger
Cam Salzberger 2020년 9월 28일
Hello Natalie,
I'm making some guesses about what you are looking for here. The situation is that you have these files in a single directory:
  • 123_FM01_HF_0221.txt
  • 123_FM02_HF_0221.txt
  • 123_FM67_HF_0221.txt
And currently your code is designed to open files in order based on the file name. Something like:
filenumberfinal=dir( '*FM*.txt');
out=size(filenumberfinal,1);
for k = 1:out
fname = sprintf('123_FM%02d_HF_0221.txt')
...
end
And that only works if the filenames have contiguous numbers, because you are counting from 1 to the number of files you have found.
If that's the case, then my suggestion is to instead use the output of "dir" to operate on the files that match the pattern.
dirInfo = dir('*FM*.txt');
for k = 1:numel(dirInfo)
fname = dirInfo(k).name;
...
end
Let me know if I'm misunderstanding something though.
-Cam

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by