Can I nest objects in MATLAB?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
per isakson
am 29 Feb. 2016
Bearbeitet: per isakson
am 3 Mär. 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.
Siehe auch
Kategorien
Mehr zu Class File Organization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!