Convert cell array of string arrays to a single string array
22 次查看(过去 30 天)
显示 更早的评论
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)
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
2023-3-25
Hi Charles
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{:})
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!