Appending string to Matlab array
Solution 1
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
Solution 2
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
Solution 3
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
Solution 4
Use strcat
function to append using one line code without using loop:
A={'food','banana','orange'}
A = 'food' 'banana' 'orange'
A = strcat(A,'s')
A = 'foods' 'bananas' 'oranges'
Solution 5
name=[];
for_loop
filename = 'string';
name=[name; {filename}];
end
Admin
Updated on October 18, 2020Comments
-
Admin over 3 years
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
-
Andrew Janke about 14 yearsUsing the { ... } to construct iteratively like this will end up with a nested cell array like a tree or a Lisp list, not a cellstr. How about "strs = {'a string'}; for i=1:3; strs = [strs; {new_string(i)}]; end" or "... strs{end+1} = new_string(i); ..."?
-
Joseph Lisee almost 14 yearsWow, thanks for the {end+1} syntax, I didn't even know "end" existed in that context.
-
Yauhen Yakimovich about 12 yearsYes {end+1} is much better than {length(..)+1}!
-
Sibbs Gambling over 7 yearsplus 1; thanks! Didn't know
strcat
works for uneven-sized concatenation! -
Danijel almost 6 yearsI need to use the
names
as input tofopen
, however,fopen
is complaining that it's a wrong type:cell
. How would I convert cell type to string?