Convert cell array of string arrays to a single string array
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Paul
am 25 Mär. 2023
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{:})
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!