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
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With