How to convert a layered structure into arrays.
6 次查看(过去 30 天)
显示 更早的评论
I have a structure like this
A.a.b.first, A.a.b.second, A.a.b.third
A.c.d.first, A.c.d.second, A.c.d.third
A.e.f.first, A.e.f.second, A.e.f.third
I want to extract the fields "first", "second" and "third" into arrays so that one array has all the firsts, another has all the seconds, and a thrid and all the thirds. Is there a simulink method to use or a matlab function? I am currently brute forcing it in matlab code. That is,
B(1) = A.a.b.first
B(2) = A.c.d.first
B(3) = A.e.f.first
and so forth. So it would be much better to have a loop or something even more streamlined.
4 个评论
Matt J
2021-3-18
编辑:Matt J
2021-3-18
Are the desired fields always at a fixed depth (4 fields deep in your example)? Also, if the field names are not a simple alphabetical progression, what decides the order of the elements in B(i)? We need to know the general pattern before a solution can be recommended.
采纳的回答
Matt J
2021-3-18
编辑:Matt J
2021-3-18
Here's a way you can recursively search down through a tree of nested structs. Since I don't know how you want to handle multiple occurrences of the target field name (e.g. "first") on the same branch of the treee, I propose one possibility:
A.b.c.d.e.first=3;
A.g.h.first=4;
out = findField(A,'first')
function out=findField(S,tfield)
if ~isstruct(S)
out=[];
elseif isfield(S, tfield)
out=S.(tfield); %found a match
else%recurse
f=fieldnames(S);
if numel(f)==1
out=findField( S.(f{1}) , tfield);
else
for i=1:numel(f)
out{i}=findField( S.(f{i}) , tfield);
end
end
end
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!