Appending string to Matlab array

Viewed 101672

How do I append a string to a Matlab array column wise?

Here is a small code snippet of what I am trying to do:

for_loop
  filename = 'string';
  name=[name; filename]
end
9 Answers

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 =

hi
there

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
name=[];
for_loop
    filename = 'string';
    name=[name; {filename}];
end

For completeness, one should also mention the new string class introduced in MATLAB R2016b; a container for text data along with a set of functions for easy text manipulation.

To compare it against my other example, here is how to allocate a string array:

N = 10;
names = strings(1,N);
for i=1:N
    names(i) = 'string';
end

And here is how to dynamically expand the array without preallocation:

names = strings(0);
for i=1:10
    names(end+1) = 'string';
end

(Of course if the strings are all the same or form a sequence with a pattern, there are better ways to create the array without a loop. The above was just an example of filling the array one-by-one).

The string container can also convert to/from character arrays and cell arrays of chars.

You are going the right way. Use {} to build a cell array, like this

stringtable = 'a string';
for i = 1:3
    stringtable = {stringtable;new_string(i)}
end

should do what you want.

Related