Check if a nested field exists in a structure OR nested property in an object

18 次查看(过去 30 天)
I'm working with nested structures with different fields that may hold objects with properties, and any mix of such datatypes. I noticed there are several questions about finding whether nested fields in a struct exist, but couldn't find an answer for finding whether nested properties of objects exist. For example, I have an object with a property, that holds another object with another property, itself being a struct with fields:
obj2.prop2 = struct('field','value');
obj1.prop1 = obj2;
Does "obj1.prop1.prop2.field" exist?
I wrote something that may be useful:
function tf = ischild(o, varargin)
if isempty(varargin), tf = true; return; end
if (numel(varargin)==1) && contains(varargin{1},'.')
varargin = strsplit(varargin{1},'.');
end
child = varargin{1};
if (isobject(o) && isprop(o,child)) || (isstruct(o) && isfield(o,child))
tf = ischild(o.(child),varargin{2:end});
else
tf = false;
end
end
You can use it in two different ways:
ischild(obj1,'prop1.prop2.field')
ischild(obj1,'prop1','prop2','field')
The surprising thing, I noticed, is that MATLAB's "getfield()" works well for nested structs but not for objects, while "setfield()" works for nested objects/struct mix. So at least before calling "getfield" or "setfield", you could check if it exists with "ischild()". Hope this helps.

回答(1 个)

Shivam
Shivam 2023-9-21
Hi @Roys,
I understand that you want to know how to access fields within a nested structure. It appears that you have implemented the "ischild" function to validate the existence of a field within an object.
You can follow the below workaround to resolve the issue.
  1. Create two classes, namely “inner” and “outer” where “outer” has the property that holds an object of the “inner” class.
classdef outer
properties
innerObj
end
methods
function obj = outer(field, value)
obj.innerObj = inner(field, value);
end
function innerObjPropFromOuterObj(obj)
disp(['obj.innerObj.innerProp.field', obj.innerObj.innerProp.field]) % target value
end
end
end
classdef inner
properties
innerProp
end
methods
function obj = inner(field, value)
obj.innerProp = struct(field, value);
end
end
end
2. create an object of "outer" class.
obj = outer("field","value");
Additionally, your implementation and workflow involving the “ischild”, “getfield” and “setfield” functions also appear to be correct.
I hope this helps.

类别

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