简体   繁体   中英

MATLAB: Convert cell array of 1D strings to 2D string

Recent versions of MATLAB have strings , which are N-Dimensional matrices of character vectors. I have a cell array of such 1D strings that I would like to combine into a single 2D string, but I am having a lot of trouble doing so. The join , strjoin and strcat functions work on the characters arrays inside the string, and cell2mat doesn't work:

>> cell2mat({strings(1, 4); strings(1, 4)})
Error using cell2mat (line 52)
CELL2MAT does not support cell arrays containing cell arrays or objects. 

Is there any good way to do this? I expect the output in the above case to be a 2x1 string object.

string objects behave just like any other datatype ( double , char , etc.) when it comes to concatenation with the same type. As long as you want the result to also be a string object, use normal concatenation.

result = [strings(1, 4); strings(1, 4)];

Or you can use cat or vertcat to be more explicit

result = cat(1, strings(1, 4), strings(1, 4));
result = vertcat(strings(1, 4), strings(1, 4));

Alternately you could use indexing to sample the same element twice

result = strings([1 1], 4);

If your data is already in a cell array, then you can use {:} indexing to generate a comma-separated list that you can pass to cat

C = {string('one'), string('two')};
result = cat(1, C{:})

As a side-note, there is no such thing as a 1-dimensional array in MATLAB. All arrays are at least two dimensions (one of which can be 1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM