Can I nest objects in MATLAB?
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (1)
per isakson
el 29 de Feb. de 2016
Editada: per isakson
el 3 de Mzo. de 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.
Ver también
Categorías
Más información sobre Class File Organization en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!