Concatenate fields of a structure
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2022-4-14
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 个评论
更多回答(3 个)
Ferdi
2022-4-15
2 个评论
Stephen23
2022-4-15
"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{:})
另请参阅
类别
在 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!