# How to convert a layered structure into arrays.

조회 수: 1(최근 30일)
John Petersen 2021년 3월 18일
편집: Matt J 2021년 3월 18일
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표시숨기기 이전 댓글 수: 3
John Petersen 2021년 3월 18일
편집: John Petersen 2021년 3월 18일
No. Most are four, but some are only three deep. There is a bus in simulink that defines the order. Is it possible to use that? There is also an enum that is used in the code that defines the same order.

댓글을 달려면 로그인하십시오.

### 채택된 답변

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')
out = 1×2 cell array
{[3]} {[4]}
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
##### 댓글 수: 1표시숨기기 없음
John Petersen 2021년 3월 18일
Thanks, that looks like it might work.

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

Matt J 2021년 3월 18일
편집: Matt J 2021년 3월 18일
A more automated option,
f=string(num2cell('a':'z'));
for i=1:13
B(i)=A.( f(2*i-1) ).( f(2*i) ).first;
C(i)=A.( f(2*i-1) ).( f(2*i) ).second;
D(i)=A.( f(2*i-1) ).( f(2*i) ).third;
end
##### 댓글 수: 1표시숨기기 없음
John Petersen 2021년 3월 18일
편집: John Petersen 2021년 3월 18일
I was looking for a more general approach that was able to extract the last fields in the structure. The fields are not actually 'a', 'b', 'c'....

댓글을 달려면 로그인하십시오.

### 범주

Find more on Structures 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!

Translated by