which function to us to check if a struct name exists

15 views (last 30 days)
Dear all,
I am importing data in the form of a struct and the struct name is not the same everytime. Sometimes the struct is named a.b.c.d and sometimes it is named a.b.x.d. or a.b.c.x
I want to to perform a check if a.b.c.d exists before continueing the script.
  1 Comment
Stephen23
Stephen23 on 5 Apr 2022
Using the correct terminology would help you:
a.b.x.d
^ variable
^ field
^ field
^ field
There are multiple structures involved here (not one as you wrote), it helps to describe their relationship correctly.

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 5 Apr 2022
Use function isfield
  11 Comments
Bruno Luong
Bruno Luong on 5 Apr 2022
I prefer the syntax with single input and nested field separate with the dot '.' character. I have made my own recusrive getfield ans setfield without try/catch, I might have an rrecursive isfield, just can't find it right now.
But for sure if there is a stock functions I'll use it instead.
Stephen23
Stephen23 on 5 Apr 2022
a.b.c.d = 1;
isfieldx(a, 'b', 'c', 'd') % true
ans = logical
1
isfieldx(a, 'b', 'x', 'q') % false since b does not have a field x
ans = logical
0
function isf = isfieldx(s,varargin);
isf = false;
try
getfield(s,varargin{:});
isf = true;
end
end

Sign in to comment.

More Answers (1)

Bruno Luong
Bruno Luong on 5 Apr 2022
try/catch after reading your struct
try
data = a.b.c.d;
catch
try
data = a.b.x.d;
try
data = a.b.c.x;
catch
error('I''m too tired to try something else')
end
end
end

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!