Hi David,
I understand you are encountering an issue when trying to access property values of an empty object.
When creating classes in MATLAB, the default value for properties is the empty array ('[]'). It sounds like your class constructor can handle different numbers of input arguments. If this is the case, then you might be using 'varargin' as the constructor input argument so that you can handle the different number of inputs. I have included a sample class below that handles no inputs and two inputs:
classdef example < handle
properties
a
b
end
methods
function obj = example(varargin)
if nargin == 2
obj.a = varargin{1};
obj.b = varargin{2};
end
end
function set.a(obj,val)
obj.a = val;
end
function out = get.a(obj)
out = obj.a;
end
function set.b(obj,val)
obj.b = val;
end
function out = get.b(obj)
out = obj.b;
end
function out = dummy_sum(obj)
out = obj.a + obj.b;
end
end
end
With this class, I can perform the following commands and get the displayed outputs:
>> obj1 = example()
obj1 =
example with properties:
a: []
b: []
>> obj2 = example(1,2)
obj2 =
example with properties:
a: 1
b: 2
>> obj1.dummy_sum()
ans =
[]
>> obj2.dummy_sum()
ans =
3
>> obj1.a
ans =
[]
>> obj2.a
ans =
1
In this example, I do not encounter the same issue you are having with accessing a property value of an empty object. One thing that might be causing some issues is the syntax you are using for creating the empty object: myObject.empty. I am not sure if this is pseudo-code or the actual syntax you are using; if this is how you are actually instantiating the empty object, it might not be handling the property initialization properly. You might want to try a similar format to the example above, using the 'varargin' input to handle multiple forms of object instantiations.
I hope this helps.
Matt Cohen
Best Answer