Convert cell array of string arrays to a single string array

109 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Paul
Paul il 25 Mar 2023
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"

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by