MATLAB Answers

Problem with using isfield

15 views (last 30 days)
Veronika
Veronika on 6 Apr 2017
Commented: samuel okeleye on 10 Aug 2018
Dear all,
I have one structure with 4 fields and I would like to use function isfield for other work.
I have this part of code:
if isfield(shape,'leftLung',shape,'rightLung',shape,'spine');
tmp2 = shape.spine{1};
tmp3 = shape.leftLung{1};
tmp4 = shape.rightLung{1};
and I have this error:
Error using isfield
Too many input arguments.
Error in Newmodel (line 115)
if isfield(shape,'leftLung',shape,'rightLung',shape,'spine');
Can you please advise me, how to change this part of code for good function? Thank you for your answers.

  2 Comments

Jan
Jan on 6 Apr 2017
The shown code has no valid Matlab syntax. Therefore the readers cannot know its intention. Suggesting a wrong idea might be more confusing then useful for you.
samuel okeleye
samuel okeleye on 10 Aug 2018
if isfield(shape,{'leftLung','rightLung','spine'}); You only need one instance of the structure name and a curly bracket to cover all fields in the structure "Shape". I hope this works.

Sign in to comment.

Answers (2)

Thorsten
Thorsten on 6 Apr 2017
Edited: Thorsten on 6 Apr 2017
if isfield(shape,'leftLung')
tmp3 = shape.leftLung{1};
end
if isfield(shape, 'rightLung')
tmp4 = shape.rightLung{1};
end
if isfield(shape,'spine');
tmp2 = shape.spine{1};
end

  1 Comment

Steven Lord
Steven Lord on 6 Apr 2017
You're probably going to want to add else blocks to each of those if statements, to assign default values to tmp3, tmp4, and tmp2 if the shape struct doesn't contain fields by those names.

Sign in to comment.


Jan
Jan on 6 Apr 2017
If you have a structure with 4 fields, checking the existing of fields is not necessary. I guess:
if isfield(shape,'leftLung') && isfield(shape,'rightLung') && isfield(shape,'spine')
tmp2 = shape.spine{1};
tmp3 = shape.leftLung{1};
tmp4 = shape.rightLung{1};
end

  0 Comments

Sign in to comment.


Translated by