I know how to initialise an array of objects:
arrayOfA(3,2) = ClassA();
for i = 1:3
for j = 1:2
arrayofA(i,j) = ClassA(...);
end
end
but when I try this for a property:
classdef ClassB
properties
arrayOfA;
...
end
methods
%% Constructor
function b = ClassB(...)
b.arrayOfA(3,2) = ClassA(); % Error!
...
end
end
I get the exception Conversion to double from ClassA is not possible.
I have read that when a default value for a property is not provided, it is initialised to an empty array of doubles. This explains the exception, but how do I set the default value of arrayOfA such that I can fill it with objects?
I have tried:
properties
arrayOfA(3,2) = ClassA;
but this gives the exception Unbalanced or unexpected parenthesis or bracket.
Edit: I am using MATLAB R2015b, which turns out to affect the solution - see below.
In the property definition of arrayOfA, you should be able to set it as:
properties
arrayOfA = ClassA.empty
end
empty is a built-in method of all non-abstract classes for exactly this purpose. It will initialise the array to an empty array of ClassA, rather than an empty array of doubles.
Starting in version R2016a, you can restrict the property type like so:
classdef ClassB
properties
arrayOfA ClassA
...
end
methods
% Constructor
function b = ClassB(...)
b.arrayOfA(3, 2) = ClassA();
...
end
end
Note there's no = sign. This will require that values assigned to this property must be of class ClassA, of any size.
Starting in version R2017a, you can also restrict the size as per the documentation here:
classdef ClassB
properties
arrayOfA(3, 2) ClassA
...
end
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With