Appending string to Matlab array Appending string to Matlab array arrays arrays

Appending string to Matlab array


You need to use cell arrays. If the number of iterations are known beforehand, I suggest you preallocate:

N = 10;names = cell(1,N);for i=1:N    names{i} = 'string';end

otherwise you can do something like:

names = {};for i=1:10    names{end+1} = 'string';end


As other answers have noted, using cell arrays is probably the most straightforward approach, which will result in your variable name being a cell array where each cell element contains a string.

However, there is another option using the function STRVCAT, which will vertically concatenate strings. Instead of creating a cell array, this will create a 2-D character matrix with each row containing one string. STRVCAT automatically pads the ends of the strings with spaces if necessary to correctly fill the rows of the matrix:

>> string1 = 'hi';>> string2 = 'there';>> S = strvcat(string1,string2)S =hithere


As noted elsewhere, in MATLAB all strings in an array must be the same length. To have strings of different lengths, use a cell array:

name = {};for i = somearray  name = [name; {string}];end