Convert cell array of string arrays to a single string array

조회 수: 102 (최근 30일)
Charles
Charles 2023년 3월 25일
댓글: Charles 2023년 3월 25일
Say I have a cell array defined as follows:
my_cell = cell(5,1);
% Assign some values
my_cell{1} = "event A";
my_cell{3} = ["event B";"event A";"event C"];
my_cell{4} = ["event C";"event A"];
I want to transform the cell array to a single column of strings = ["event A";"event B";"event A";"event C";"event C";"event A"]. It seems like cell2mat should work for this, but it gives an error:
>> cell2mat(my_cell)
Error using cell2mat
All contents of the input cell array must be of the same data type.
Even if I replace the empty cells with "", it still gives an error:
>> my_cell{2} = "";
>> my_cell{5} = "";
>> cell2mat(my_cell)
Error using cell2mat
CELL2MAT does not support cell arrays containing cell arrays or objects.
In the actual application, each string could have any length, and the resulting vector will have ~10^6 strings. I could obviously just loop over the cell array and construct my string array that way, but this is something I would expect there to be quick 1-line solution for.
Also, since there is just a small set of possible string values, I could also just encode them as numbers, since the following works fine.
my_cell = cell(5,1);
% Assign some values
my_cell{1} = 1;
my_cell{3} = [2;1;3];
my_cell{4} = [3;1];
my_vector = cell2mat(my_cell)
my_vector = 6×1
1 2 1 3 3 1
But in my actual program, I would rather keep my data encoded as strings since it's easier to understand the code that way.
Is there a nice solution for this?

채택된 답변

Paul
Paul 2023년 3월 25일
Hi Charles
Use vertcat with a comma separated list as the input
my_cell = cell(5,1);
% Assign some values
my_cell{1} = "event A";
my_cell{3} = ["event B";"event A";"event C"];
my_cell{4} = ["event C";"event A"];
s = vertcat(my_cell{:})
s = 6×1 string array
"event A" "event B" "event A" "event C" "event C" "event A"

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by