0
votes

I am using a loop to create my cell array. It contains the string 'A1' to 'A10'. Is there a way to iterate without using a loop ?

a = cell( 10, 1 );
for i = 1 : length( a )
   a{i} = [ 'A', num2str( i ) ];
end

a = 

    'A1'
    'A2'
    'A3'
    'A4'
    'A5'
    'A6'
    'A7'
    'A8'
    'A9'
    'A10'
2
What is wrong with the loop? I bet it’s faster than any of the alternatives below.Cris Luengo

2 Answers

3
votes

I assume you want to build a without a loop. Let N = 10 as per your example.

Approach 1

a = sprintf('A%i ', 1:N);
a = a(1:end-1);
a = strsplit(a).';

This builds a char vector with a space after each number, removes the final space, splits on spaces, and transposes.

Approach 2

Another approach:

a = deblank(cellstr(strcat('A', strjust(num2str((1:10).'), 'left'))));

This concatenates 'A' with the numbers to form a 2D char array with some spaces; moves the spaces in each row to the right; converts each row into a cell; and removes trailing spaces on each cell.

3
votes

If you have R2017a or later consider using string arrays instead of cell array of char vectors. You can create your string array using

"A"+(1:10)'