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

Time:10-20

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.

CodePudding user response:

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.

  • Related