Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler code to create a cell array of char type with the same prefix + sequential indices?

I want to create a cell array with the same prefix + sequential indices, e.g., {'a1','a2','a3','a4','a5'}.

The code below can generate the desired output, but I guess there should be much shorter code can do.

>> strcat('a',arrayfun(@num2str,1:5,'UniformOutput',false))

ans =

  1×5 cell array

    {'a1'}    {'a2'}    {'a3'}    {'a4'}    {'a5'}

It would be greatly appreciated if someone can share ideas to make it in a simpler and more elegant manner.

like image 839
ThomasIsCoding Avatar asked Feb 22 '26 05:02

ThomasIsCoding


1 Answers

This is not exactly the same, but if you use the new (not so new any more) string arrays, you can do:

"a" + (1:5)

This returns:

ans = 

  1×5 string array

    "a1"    "a2"    "a3"    "a4"    "a5"

In general, the "new" strings are more convenient to use than the old char arrays, for certain things. If you want to manipulate individual characters, it is best to continue using char arrays, but for general string manipulation, and especially manipulation of many strings at once, string arrays provide much better functionality.

like image 160
Cris Luengo Avatar answered Feb 25 '26 01:02

Cris Luengo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!