回调,计时器和OOP方法:帮助使用方法作为计时器回调

时间:2011-04-22 06:38:47

标签: matlab

Matlab向导的世界。

6年的Matlab用户,刚刚开始在Matlab中使用OOP。 我正在尝试使用一个方法作为位于构造函数中的计时器的回调,但它不起作用。我错过了什么? 请赐教。

由于


classdef Vehicle
% Vehicle
% Vehicle superclass

properties
    Speed             % [Km/Hour]
    Length            % [Meter]
    Width             % [Meter]
    Driver            % Properties of the driver
    Current_Route     % Current route
    Route_Percent     % Which Percent of the route the vehicle is in
    Route_Direction   % Driving forward or backeard on the routhe
    Last_Action_Time  % The time stamp for the last action of the vehicle
end

methods
    function this = Vehicle(varargin)
        this.Speed            = varargin{1}; % The speed of the car
        this.Current_Route    = varargin{2}; % What route the vehicle is on
        this.Route_Percent    = varargin{3}; % Where on the routeh is the vehicle
        this.Route_Direction  = varargin{4}; % To what direction is the car moving on the route
        this.Last_Action_Time = clock;       % Set the time the thisect was creted
        Progress_Timer = timer('TimerFcn', @Progress, 'Period', varargin{4}, 'ExecutionMode' ,'FixedRate'); % Sets a timer for progressing vehicle position
        start(Progress_Timer) % Starts the timer
    end

    function this = Progress(this)
        if (this.Route_Percent >= 0 && this.Route_Percent <= 100) % If the vehicle does not exceed the route map
            this.Route_Percent = this.Route_Percent + ...
                this.Route_Direction * this.Speed * etime(clock,this.Last_Action_Time)/3600 / this.Current_Route.Length * 100
            this.Last_Action_Time = clock; % Set the time the progress was done
        else
            this.delete;           % Vehicle is no longer relevant
            stop(Progress_Timer);  % Stops the timer
        end
    end
end
end 

1 个答案:

答案 0 :(得分:1)

方法不像子功能。这意味着您希望将对象传递给计时器功能。

Progress_Timer = timer('TimerFcn',@()Progress(this))

此外,您希望vehicle成为句柄类,以便每当对象更新时,函数句柄中的this都会更新。

但是,您可能不想使用计时器,而是希望使用set-methods,只要其中一个属性发生更改,就会更新车辆的状态。这将更加透明。