필터 지우기
필터 지우기

How do I make a script to show the field names of struct in a struct

조회 수: 4 (최근 30일)
Emily
Emily 2022년 4월 21일
댓글: Matt J 2022년 4월 22일
I currently have the code below to list out only the structs.
sTable=struct2table(s);
sStruct=sTable(:,vartype('struct'));
Inside the table there are 3 1x1 structs that I wanted to access.
I can get there via clicking on the variables workspace or using individual fieldnames
a=fieldnames(sStruct.v1_abc)
but I wanted to have a script to automatically access it by entering the first colnmn names show the fields.
Thanks in advance.
  댓글 수: 2
Matt J
Matt J 2022년 4월 21일
Please attach sStruct and also clarify "by entering the first colnmn names show the fields".
Emily
Emily 2022년 4월 21일
a1='abcd';
a2=[1 2 3];
s.a=char(a1,a2);
s.b.a = ones(3);
s.b.b = eye(4);
s.c.c = magic(5);
s.d=char(a2,a1);
For example, for the s Struct above I want it to show the fieldnames for s.b and s.c without going to the variables workspace.

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

채택된 답변

Matt J
Matt J 2022년 4월 21일
Something like this?
a1='abcd';
a2=[1 2 3];
s.a=char(a1,a2);
s.b.a = ones(3);
s.b.b = eye(4);
s.c.c = magic(5);
s.d=char(a2,a1);
showsubfields(s,'b','c')
Field: b a b Field: c c
function showsubfields(S,varargin)
for i=1:numel(varargin)
fn=varargin{i};
if ~isstruct(S.(fn)); continue; end
disp("Field: "+fn)
subfns=fieldnames(S.(fn));
disp(char(" "+subfns))
end
end
  댓글 수: 6
Emily
Emily 2022년 4월 22일
That's perfect! Thank you so much!
Matt J
Matt J 2022년 4월 22일
You're welcome, bu please Accept-click to indicate that it worked.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by