What to do about zeros in filenames when importing data to cell using sprintf ...

This seems like it would be a fairly common problem, yet I haven't found any documentation or on Answers relating to this. So if anyone has a handy link, that'd be great (maybe it's too specific).
I have ten datasets in *.MAT format named sequentially:
Position01.mat, Position02.mat ... through to ... Position10.mat
Importing Position01 to Position09 to a cell is no issue, but opening and importing "Position10.mat" is made tricky because the number in its filename is "formatted" differently; specifically, doesn't start with zero. So, I'm wondering if I can keep my filenames, which keep the files nicely organised and in order outside MATLAB and find a workaround for dealing with "Position10.mat".
I'm currently using these lines to import the files ...
NumFiles = 10;
AudioCell = cell(1, NumFiles);
for k = 1: NumFiles
Position = sprintf('Position0%d.mat', k);
AudioCell{k} = importdata(Position);
end
It imports Position01 - Position09 exactly how I want, but Position10 has me stumped. Is changing the *.MAT filenames to "Position1", "Position2" and so on, my only decent option? So ...
Position = sprintf('Position%d.mat', k);
Thanks in advance!

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 10월 18일
편집: Ameer Hamza 2020년 10월 18일
No, this is not the only option. The correct way is to use format specifier of sprintf() to add zeros automatically
sprintf('Position%02d.mat', k);
This will try to replace %02d with 2 digits. If k = 1 to 9, then it will append a zero.

댓글 수: 5

Ah, excellent! So, "&02d" denotes two digits?
What is that method/symbol called (the "%02d" part)? Hopefully I can find documentation that has all those kind of codes used for indicating where and what type of characters the code should look for (I hope that makes sense). Thanks!
I am glad to be of help!
I really appreciate it. Thanks so much again!
And thanks a bunch for the link! I reckon sometimes just finding out the correct terminology for something - "formatSpec", for example, which is a term I hadn't even come across when trying to solve this - makes such a huge difference when looking things up; vague search terms make wading through the results a frustrating task. Maybe sometimes the best questions to ask are just things like "what's this oscure looking character sequence called?". Hehe.
Cheers!
Ture, sometimes all one needs is a correct hint, and the rest is easy to figure out.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 10월 18일

댓글:

2020년 10월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by