MATLAB Answers

How to run a for loop every one second ?

Asked by Arun Badigannavar on 9 May 2013

In M Script how to execute a for loop every one second?

  2 Comments

per isakson
on 9 May 2013

Did you consider to use the timer?

    doc timer
Arun Badigannavar on 10 May 2013

ya but i am unable to do it without pause command

Products

No products are associated with this question.

1 Answer

Answer by Friedrich
on 10 May 2013
Edited by Friedrich
on 10 May 2013
 Accepted answer

Try this,

function a = test
a = timer('ExecutionMode','fixedRate','Period',1,'TimerFcn',@myfun);
start(a);
end
function myfun(obj,evt)
for i=1:3
    disp(datestr(now));
end
disp('===============');
end

and call it with

my_timer = test();

When you like to stop the timer call

stop(my_timer)

Or in the case you want to wait until the timer is done and you know how often the for loop should be triggered do this:

function a = test
a = timer('ExecutionMode','fixedRate','Period',1,'TimerFcn',@myfun,'TasksToExecute',10);
start(a);
wait(a);
disp('timer done')
end
function myfun(obj,evt)
for i=1:3
    disp(datestr(now));
end
disp('===============');
end

Make sure the tme myfun needs to run is lower than 1 second.

  0 Comments


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today