Struggling to store indexing variable as an array.

I am trying to store a list of file names which have been retrieved from a folder.
Any help would be appreciated; here is what I have so far:
File = zeros(1,10);
for i=1:10
File(1,i) = sprintf('%s%05d%s', 'A', i, '.dat');
end
I get the error message: "Subscripted assignment dimension mismatch."
I would like the files to be stored as:
File = [A00001.dat A00002.dat ... A0000N.dat]
Hopefully it is clear what I'm trying to achieve.
If I use the code:
File = zeros(1,10);
for i=1:10
File = sprintf('%s%05d%s', 'A', i, '.dat');
end
It runs; however, it only stores the final File name (in this case, "A00010.dat") rather than a 1x10 array of the first 10 File names.
Thanks

 采纳的回答

Each character of a string is one element of an array. So File = zero(1, 10) will only let you store 10 characters, not 10 strings.
Because all your strings are the same length, you could store all of them in a 2D char array, with each row a string, and each column one of the 10 characters.
filenames = zeros(10, 10); %space for 10 strings of 10 characters
for row = 1:10
filenames(row, :) = sprintf('%s%05d%s', 'A', row, '.dat');
end
%to access a string:
s = filenames(stringindex, :)
However, much better would be to store your strings in a cell array, where each string is an element of the cell array. It's much safer, strings can be different sizes, the above will error if a string is not exactly 10 characters:
filenames = cell(1, 10); %space for 10 strings of arbitrary length
for sidx=1:10
filenames{sidx} = sprintf('%s%05d%s', 'A', sidx, '.dat');
end
%to access a string:
s = filenames{stringindex}
Finally, note there is an undocumented/unsupported function (use at your own peril) that can replace the creating and filling of the cell array: sprintfc:
filenames = sprintfc('A%05d.dat', 1:10)

1 个评论

filenames = cell(1, 10); %space for 10 strings of arbitrary length
for sidx=1:10
filenames{sidx} = sprintf('%s%05d%s', 'A', sidx, '.dat');
end
This worked perfectly, thanks for your help.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by