【问题标题】:Matlab, timed iteration over a matrixMatlab,矩阵上的定时迭代
【发布时间】:2012-12-08 14:39:15
【问题描述】:

我正在开发一个模拟器作为一个爱好项目。我遇到问题的特定函数从矩阵中取出一行并每 50 毫秒提供给一个函数,但我是 Matlab 脚本的新手,需要一些帮助。

每次计时器点击时,矩阵中的下一行应提供给函数“simulate_datapoint()”。 Simulate_datapoint() 获取行,执行一些计算魔术并更新轨道数组中的复杂“轨道”对象。

这是尝试解决此问题的完全倒退的方式,还是我接近可行的解决方案?任何帮助将不胜感激。

以下是我现在无法使用的:

function simulate_data(data)
    if ~ismatrix(data)
        error('Input must be a matrix.')
    end

    tracks = tracks_init(); % create an array of 64 Track objects.
    data_size = size(data,1); % number of rows in data.
    i = 0;
    running = 1;

    t = timer('StartDelay', 1, 'Period', 0.05, 'TasksToExecute', data_size, ...
          'ExecutionMode', 'fixedRate');
    t.StopFcn = 'running = 0;';
    t.TimerFcn = 'i = i+1; simulate_datapoint(tracks, data(i,:));';

    disp('Starting timer.')
    start(t);

    while(running==1)
        % do nothing, wait for timer to finish.
    end

    delete(t);
    disp('Execution complete.')
end

【问题讨论】:

    标签: arrays matlab matrix timer


    【解决方案1】:

    您已经非常接近工作原型了。一些笔记。

    1) 您的字符串为 timerFn 和 stopFn 指定的 MATLAB 函数不共享相同的内存地址,因此变量“i”是没有意义的,并且不会在它们之间共享

    2) 使用 waitfor(myTimer) 等待...等待计时器。

    下面的代码应该可以帮助您入门,其中我使用了“嵌套函数”,它与调用函数共享范围,因此它们了解并与调用范围共享变量:

    function simulate
    
        iterCount = 0;
        running = true;
    
        t = timer('StartDelay', 1, 'Period', 0.05, 'TasksToExecute', 10, ...
              'ExecutionMode', 'fixedRate');
    
        t.StopFcn = @(source,event)myStopFn;
        t.TimerFcn = @(source,event)myTimerFn;
    
        disp('Starting timer.')
        start(t);
        waitfor(t);
        delete(t);
        disp('Execution complete.')
    
        % These are NESTED functions, they have access to variables in the
        % calling function's (simulate's) scope, like "iterCount"
        % See: http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html
        function myStopFn
            running = false;
        end
        function myTimerFn
            iterCount = iterCount + 1;
            disp(iterCount);
        end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多