Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 835
Name Avatar asked Feb 18 '10 13:02

Name


People also ask

How do you combine an array of strings in MATLAB?

newStr = join( str ) combines the text in str by joining consecutive elements of the input array, placing a space character between them. str can be a string array or a cell array of character vectors. newStr has the same data type as str .

How do you add to a string in MATLAB?

str = append( str1,...,strN ) combines the text from str1,...,strN . Each input argument can be a string array, a character vector, or a cell array of character vectors. If any input is a string array, then the output is a string array.

How do you combine strings in an array?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do you add a value to an array in MATLAB?

C = A + B adds arrays A and B by adding corresponding elements. If one input is a string array, then plus appends the corresponding elements as strings. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.


2 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 
like image 175
Amro Avatar answered Oct 07 '22 19:10

Amro


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 
like image 44
gnovice Avatar answered Oct 07 '22 18:10

gnovice