Concatenate fields of a structure
16 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Stephen23
on 14 Apr 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 Comments
More Answers (3)
Ferdi
on 15 Apr 2022
2 Comments
Stephen23
on 15 Apr 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{:})
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!