Can I nest objects in MATLAB?
Afficher commentaires plus anciens
Is it possible to nest objects in MATLAB? For example, say that I have a 'car' class and ultimately a 'car' object. The car has properties like name and color. However, I want an 'wheel' property with a class and properties of it's own to belong to the 'car'. There are four wheels on my car and the wheels can be different sizes (front to back).
With the code below, I am able to create a nested object scenario. I can retrieve the properties of the lone wheel (Car.Wheel.Width). My problem is that I don't know how to create an array of multiple wheel objects that belong to the car (Car.Wheel(2).Width...Car.Wheel(3).Width...etc)
Is this possible?
classdef carClass
properties(Access = public)
Name
Color
end
properties(SetAccess = private)
Wheel
end
methods
function obj = carClass
obj.Wheel = wheelClass;
end
end
end
and
classdef wheelClass < handle
properties
Number
Location
Width
end
end
Réponses (1)
per isakson
le 29 Fév 2016
Modifié(e) : per isakson
le 3 Mar 2016
 
In response to comment
I don't understand what problem you encounter, but here are two variants
car_1 = carClass_1;
car_1 = car_1.setWheelLocation;
car_1.dispWheelLocation
car_2 = carClass_2;
car_2 = car_2.setWheelLocation;
car_2.dispWheelLocation
which both outputs
rf
lf
lr
rr
where
classdef carClass_1
properties(Access = public)
Name
Color
end
properties(SetAccess = private)
Wheel = wheelClass.empty;
end
methods
function obj = carClass_1
obj.Wheel(1,4) = wheelClass;
end
function obj = setWheelLocation( obj )
obj.Wheel(1,1).Location = 'rf';
obj.Wheel(1,2).Location = 'lf';
obj.Wheel(1,3).Location = 'lr';
obj.Wheel(1,4).Location = 'rr';
end
function dispWheelLocation( obj )
obj.Wheel(1,:).Location
end
end
end
and
classdef carClass_2
properties(Access = public)
Name
Color
end
properties(SetAccess = private)
Wheel
end
methods
function obj = carClass_2
obj.Wheel = wheelClass;
obj.Wheel(1,end+1) = wheelClass;
obj.Wheel(1,end+1) = wheelClass;
obj.Wheel(1,end+1) = wheelClass;
end
function obj = setWheelLocation( obj )
obj.Wheel(1,1).Location = 'rf';
obj.Wheel(1,2).Location = 'lf';
obj.Wheel(1,3).Location = 'lr';
obj.Wheel(1,4).Location = 'rr';
end
function dispWheelLocation( obj )
obj.Wheel(1,:).Location
end
end
end
 
I don't fully understand why you chose to make wheelClass a handle class and carClass a value class, but that's a different question.
1 commentaire
jmsrz
le 1 Mar 2016
Catégories
En savoir plus sur Class File Organization dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!