Is it possible to check for existence of fields in nested structures with isfield in MATLAB 8.1 (R2013a)?
38 次查看(过去 30 天)
显示 更早的评论
I have the following structure
a.b.c = 1;
I know it is possible to search for the nested
isfield(a.b,'c')
But I would like to check for the existence of the field 'c' even when I am not sure that the field 'b' exists, e.g.
isfield(a,'b.c');
采纳的回答
MathWorks Support Team
2013-10-25
There is no MATLAB function to determine the existence of fields in nested structures. The only workaround is to check separately for the existence of 'b' and of 'c':
isfield(a, 'b') && isfield(a.b, 'c')
0 个评论
更多回答(1 个)
Steven Lord
2022-12-16
Another approach that uses neither eval nor repeated calls to isfield is to use getfield.
a.b.c = 1;
isNestedField(a, 'b.c')
isNestedField(a, 'b.d')
isNestedField(1:10, 'a')
function tf = isNestedField(s, thefields)
fieldlist = split(thefields, '.');
try
getfield(s, fieldlist{:});
tf = true;
catch
tf = false;
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!