2011-04-24 120 views
7

我有一個類,像這樣:Matlab的面向對象編程:對多個對象設置和獲取屬性

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 

我以細胞的形態創建我的汽車類對象(不要問我爲什麼 - 這是一個外行對全局設置解決方法):

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; 

我的問題:1。 有沒有辦法將所有三個對象活躍在一個命令? 2.有沒有辦法在一個命令中獲得所有三個對象的速度? 3.有沒有辦法在一個命令中查詢哪些車輛比X快?

感謝 加布裏埃爾

回答

8

對於同一類的成員,你可以使用圓括號(規則排列):

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

要設置所有對象使用deal

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

你也可能是initialize an array of objects

對於您的問題(2)和(3)的語法等效於那些MATLAB結構:

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

這種矢量表示法是一種strong point of MATLAB並被廣泛使用。