Etni3s
Etni3s

Reputation: 33

Matlab, timed iteration over a matrix

I'm developing a simulator of sorts as a hobby project. The specific function i'm having trouble with takes a row from a matrix and supplies to a function every 50'th millisecond, but I'm a novice with Matlab scripting and need some help.

Each time the timer clicks, the next row in the matrix should be supplied to the function "simulate_datapoint()". Simulate_datapoint() takes the row, performs some calculation magic and updates a complex "track" object in the tracks array.

Is this a completely backwards way of trying to solve this problem or am I close to a working solution? Any help would be greatly appreciated.

Here's what I have right now that doesn't work:

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

Upvotes: 2

Views: 130

Answers (1)

Pete
Pete

Reputation: 2344

You're very close to a working prototype. A few notes.

1) Your string specified MATLAB functions for the timerFn and stopFn don't share the same memory address, so the variable "i" is meaningless and not shared across them

2) Use waitfor(myTimer) to wait... for the timer.

The following code should get you started, where I used "nested functions" which do share scope with the calling function, so they know about and share variables with the calling scope:

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

Upvotes: 1

Related Questions