Search code examples
stringmatlabcell-arrayprepend

Matlab: Prepend string to a cell array of strings


I want to prepend a string in a cell array of strings. For example, if I've:

q = {'1', '2'};
p = '3';

I want to do something like that

a = prepend(q, p);
a =
   '3'  '1'  '2'

How can I prepend a string?


Solution

  • You have a cell array of char, not strings.
    string and char mean different things since the release of R2016b. You can prepend a char array to a cell array in the same way how cell arrays are combined.

    a=[p,q] ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍ ‍‍‍‍‍‍ ‍‍
    

    In the similar way, you can also combine a cell array of char with a string array or a simple char array with a string array which will result in a string array though. The datatype can be changed later to a cell array of char if required using cellstr.