tags:

views:

1073

answers:

4

Hello,

I have this doubt.. I need to append the array of string in Matlab. Please suggest me how to do it..

I would like to append the string column wise on each iteration..

Here is a small code snippet which i am handling

<CODE>:
for_loop
 filename = 'string';
name=[name; filename]
end

Thanks Kiran

A: 

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.

High Performance Mark
Using 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); ..."?
Andrew Janke
+1  A: 

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
lindelof
that works for me. Thanks!!
Name
+4  A: 

You need to use cell arrays. If the number of iterations are know 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
Amro
Wow, thanks for the {end+1} syntax, I didn't even know "end" existed in that context.
Joe
+2  A: 

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
gnovice

related questions