which function to us to check if a struct name exists
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ruud Verschaeren
am 5 Apr. 2022
Kommentiert: Stephen23
am 5 Apr. 2022
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 Kommentar
Stephen23
am 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.
Akzeptierte Antwort
Bruno Luong
am 5 Apr. 2022
Use function isfield
11 Kommentare
Bruno Luong
am 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
am 5 Apr. 2022
a.b.c.d = 1;
isfieldx(a, 'b', 'c', 'd') % true
isfieldx(a, 'b', 'x', 'q') % false since b does not have a field x
function isf = isfieldx(s,varargin);
isf = false;
try
getfield(s,varargin{:});
isf = true;
end
end
Weitere Antworten (1)
Bruno Luong
am 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
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!