class1 as property of class2, class1 property initialization?
2 views (last 30 days)
Show older comments
SoderlingPotro
on 1 Nov 2022
Edited: Benjamin Kraus
on 2 Nov 2022
I have a class:
classdef class1
properties
prop1 = 1;
end
end
and I can easily access prop1 with:
test = class1
test.prop1
ans = 1
If I then put class1 as a property into another class e.g.:
classdef mainClass
properties
class1
end
end
I would like to access class1 propr 1 through mainClass. So I try the following but get an error:
>> test.class1(1).prop1
Index exceeds the number of array elements. Index must not exceed 0.
Why is prop1 not initialized to the value 1? Thanks
0 Comments
Accepted Answer
Benjamin Kraus
on 1 Nov 2022
In your definition of mainClass you created a property with the name class1, not the type class1.
This is what you want:
classdef mainClass
properties
class1 (1,1) class1
end
end
Just be careful using this approach. If class1 is a handle class, then all instances of mainClass will share the same class. In that case, you are better off with this approach:
classdef mainClass
properties
class1
end
methods
function obj = mainClass()
obj.class1 = class1;
end
end
end
You may also want to reconsider having a property name that matches a class name. It works, but it may be confusing.
2 Comments
Benjamin Kraus
on 2 Nov 2022
Edited: Benjamin Kraus
on 2 Nov 2022
You are correct. The default value can't be an empty vector because of the size validation, so by specifying that the size must be a scalar object of class class1, MATLAB will automatically (attempt to) create a scalar instance of that object as the default value of the property. Unless you also specify a default value, the object will be created by calling the class constructor with no input arguments. Without the (1,1) MATLAB will use a default value of class1.empty().
More Answers (0)
See Also
Categories
Find more on Structural Mechanics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!