Effacer les filtres
Effacer les filtres

How to generate sequenced file names with file extensions?

2 vues (au cours des 30 derniers jours)
Gregory Vigil
Gregory Vigil le 1 Août 2018
Modifié(e) : dpb le 1 Août 2018
What's the best way to generate sequenced file names with file extensions. The format I'm looking for is something along the lines of 'pcimage' + '0001' + '.h5', so the resulting names would be 'pcimage001.h5', 'pcimage002.h5', ..., 'pcimage2401.h5', ... etc. I was trying the following code, but because the leading 0s would change between 9 and 10 it throws an error. I could see doing it with an if statement that determines the number of digits of i, but i'd prefer a more elegant solution if one exists. Thanks for any help!
for i = 1:1:10 filename(i,:) = strcat('pcimage00', num2str(i), '.h5') end

Réponse acceptée

Greg
Greg le 1 Août 2018
Modifié(e) : Greg le 1 Août 2018
See the documentation for num2str to find the formatSpec input option. Then, your code simply becomes:
for i = 1:1:10
filename(i,:) = strcat('pcimage', num2str(i,'%04d'), '.h5');
end
In R2016b and later, this can be done without the loop:
filenames = compose('pcimage%04d.h5',1:5)'; % for cellstr output
filenames = compose("pcimage%04d.h5",1:5)'; % for string output

Plus de réponses (1)

dpb
dpb le 1 Août 2018
Modifié(e) : dpb le 1 Août 2018
On the same line...
>> ext='.jpg';
>> fn=num2str([1:4].',['pcimage%04d' ext])
fn =
4×15 char array
'pcimage0001.jpg'
'pcimage0002.jpg'
'pcimage0003.jpg'
'pcimage0004.jpg'
>>

Catégories

En savoir plus sur Characters and Strings 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!

Translated by