Matlab Object Oriented Programming: Setting and Retrieving Properties for Multiple Objects

I have a class like:

classdef Vehicle < handle %Vehicle % Vehicle superclass properties Is_Active % Does the vehicle exist in the simualtion world? Speed % [Km/Hour] end methods function this = Vehicle(varargin) this.Speed = varargin{1}; % The speed of the car this.Is_Active = true; end end end 

I am creating Vehicle class objects in the form of a cell (don't ask me why - this is a workaround for worlds):

 Vehicles{1} = Vehicle(100); Vehicles{2} = Vehicle(200); Vehicles{3} = Vehicle(50); Vehicles{1}.Is_Active = true; Vehicles{2}.Is_Active = true; Vehicles{3}.Is_Active = true; 

My questions: 1. Is there a way to set all three objects in one team? 2. Is there a way to get the speed of all three objects in one team? 3. Is there a way to request which vehicles are faster than X in one team?

Thanks Gabriel

+7
source share
1 answer

For members of the same class, you can use parentheses (regular array):

 Vehicles(1) = Vehicle(100); Vehicles(2) = Vehicle(200); Vehicles(3) = Vehicle(50); 

To set all objects, use deal :

 [Vehicles(:).Is_Active] = deal( true ); 

You can also initialize an array of objects .

For your questions (2) and (3), the syntax is equivalent to the syntax of MATLAB structures:

 speedArray = [Vehicles.Speed]; fasterThanX = Vehicles( speedArray > X ); 

This vectorization notation is a strong point of MATLAB and is widely used.

+8
source

All Articles