Appending string to Matlab array
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
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
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'
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.
If you are using two arrays like below (A and B) you can append them like what you do with other matrices.
A = {'a' ; 'b' ; 'c'};
B = {'1' ; '2' ; '3'};
Result = { A{:,1} ; B{:,1} }
Result =
'a' 'b' 'c'
'1' '2' '3'
I know that this is an old thread, but it seems as if you don't even need a loop if this is all you are doing in the loop. Could you just use a vertical concatenation?
mmm = {'str1'; 'str2'; 'str3'};
temp = {'a'; 'b'; 'c'};
mmm = [mmm; temp]
mmm =
'str1'
'str2'
'str3'
'a'
'b'
'c'
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.
精彩评论