开发者

Matlab Object Oriented Programming: Setting and getting properties for multiple objects

开发者 https://www.devze.com 2023-02-28 14:53 出处:网络
I have a class like so: classdef Vehicle < handle %Vehicle %Vehicle superclass properties Is_Active% Does the vehicle exist in the simualtion world?

I have a class like so:

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 create my Vehicle-class objects in a cell form (don't ask me why - it's a laymen's workaround for global setting):

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' active in a single command? 2. Is there a way to get all three objects' Speed in a single command? 3. Is there a way to query which vehicles are faster than X in a single command?

Thanks Gabriel


For the members of the same class you can use round brackets (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 could also initialize an array of objects in the first place.

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

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

Such vectorization notation is a strong point of MATLAB and is used extensively.

0

精彩评论

暂无评论...
验证码 换一张
取 消