Concatenate fields of a structure
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have a structure inside an app:
app.C1 struct with fields:
DHO: {{1×3 cell} {1×3 cell}}
DHOnw: {{1×3 cell} {1×3 cell}}
with:
app.C1.DHO{1}= {["ID1"]} {["GD1"]} {["ED1"]}
app.C1.DHO{2}= {["ID2"]} {["GD2"]} {["ED2"]}
and
app.C1.DHOnw{1}= {["IDnw1"]} {["GDnw1"]} {["EDnw1"]}
app.C1.DHOnw{2}= {["IDnw2"]} {["GDnw2"]} {["EDnw2"]}
The fieldnames DHO, DHOnw are not fixed, and in other cases I could have different ones.
I want to create a new “quantity” with all these fields concatenated, for example:
new={ ‘ID1’; ‘GD1’; ED1; ‘ID2’; ‘GD2’; ED2; ‘IDnw1’; ‘GDnw1’; EDnw1; ‘IDnw2’; ‘GDnw2’; EDnw2;};
to be then used as a single column of a table.
I tried with cellfun, but I was not able to get reasonable results: do you have some suggestions?
Thank you in advance for your help.
0 commentaires
Réponse acceptée
Stephen23
le 14 Avr 2022
Note that using a string array is much more efficient than storing scalar strings in a cell array.
app.C1.DHO = {{"ID1","GD1","ED1"},{"ID2","GD2","ED2"}};
app.C1.DHOnw = {{"IDnw1","GDnw1","EDnw1"},{"IDnw2","GDnw2","EDnw2"}};
app.C1
tmp = struct2cell(app.C1);
tmp = vertcat(tmp{:}).';
out = horzcat(tmp{:})
0 commentaires
Plus de réponses (3)
Ferdi
le 15 Avr 2022
2 commentaires
Stephen23
le 15 Avr 2022
"Is there a way to make it working in this more general case?"
Probably, once you specify the order that should be used for said "general case". The only reason I used VERTCAT was to provide the same order that you specified in your question. If the order is not significant, then you could use HORZCAT instead:
app.C1.Lrz = {{"One","Two"}};
app.C1.DHOnw = {{"IDnw1","GDnw1","EDnw1"},{"IDnw2","GDnw2","EDnw2"}};
app.C1
tmp = struct2cell(app.C1);
tmp = horzcat(tmp{:});
out = horzcat(tmp{:})
Voir également
Catégories
En savoir plus sur Cell Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!