0

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'
1
  • What is wrong with the loop? I bet it’s faster than any of the alternatives below. Commented Dec 26, 2018 at 1:49

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)'

1 Comment

Thank you. I need to get accustomed with string array. Since it is a new datatype, I still do not know the possibilities and limitations but I guess it will be more useful than the character datatype in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.