loop at a certain interval (Matlab) - matlab

As stated in title.
I want to have a certain interval time for each loop, say 60 seconds.
My problem is I have a code inside a loop to perform measurement with a external device.
This measurement takes 5-10 seconds.
So I cannot simply use pause(60) inside the loop because the interval time depends on how long each measurement takes.
Is there any way to fix the time interval of loop?

Sounds like you'd be able to use parallel threading to achieve what you want. One thread kicks off the measurement every sixty seconds, using a worker thread so that the measurement doesn't block up the time interval.
Perhaps try the batch function with something like this:
while(True)
hBatch = batch(#doMeasurement);
pause(60);
measurement = fetchOutputs(hBatch){1}
end
Better would be to use the timer function:
t = timer('TimerFcn', #doMeasurement, 'Period', 60.0);
start(t)

You want something like this:
k=1; % or any value except 0
time1=clock;
while ~(k==0)
time2=clock;
k=etime(time2,time1);
% your statements
loop

Related

Using tic/toc functions instead of a timer

Using timer objects gets too complicated especially when you have to use more than one timer so I was trying to think of alternative approaches.
I want to avoid using pause, since it stops other functions from executing. I thought of using the tic toc functions to measure elapsed time but the code I have written below does not work as I expect.
time=tic;
if(abs(toc(time)))==3 %% if 3 second past
my function
end
How can I modify this code so that it executes the command after 3 seconds?
TLDR;
A tic/toc pair and a while loop is literally no different than using pause since they both block execution of any other functions. You have to use timer objects.
A More Detailed Explanation
In order to make this work, you'd need to use a while loop to monitor if the required amount of time has passed. Also, you'll want to use < to check if the time has elapsed because the loop condition isn't guaranteed to be evaluated every femtosecond and therefore it's never going to be exact.
function wait(time_in_sec)
tic
while toc < time_in_sec
end
% Do thing after 3 seconds
fprintf('Has been %d seconds!\n', time_in_sec)
end
The unfortunate thing about a while loop approach is that it prevents you from running multiple "timers" at once. For example, in the following case, it will wait 3 seconds for the first task and then wait 5 seconds for the second task requiring a total time or 8 seconds.
wait(3)
wait(5)
Also, while the while loop is running, nothing else will be able to execute within MATLAB.
A much better approach is to setup multiple timer objects and configure them with callbacks so that they can run at the same time and they will not block any operations within MATLAB while they run. When you need multiple timer objects (which you consider to be a pain) is exactly when you have to use timer objects.
If it's really that cumbersome, write your own function which does all of the boilerplate stuff for you
function tmr = wait(time_in_sec)
tmr = timer('StartDelay', time_in_sec, ...
'ExecutionMode', 'SingleShot', ...
'TimerFcn', #(s,e)status(time_in_sec));
tmr.start()
function status(t)
fprintf('Has been %d seconds!\n', t);
end
end
wait(3)
wait(5) % Both will execute after 5 seconds
Also since the timers are non-blocking (when the callback isn't running), I can execute commands immediately after starting the timers
wait(3)
disp('Started 3 second timer')
wait(5)
disp('Started 5 second timer')
If you try this with your while loop, you'll see the while loop's blocking behavior.
you need a while loop or something to wait for time to be 3 seconds.
something like this
time=tic;
while 1
if(abs(toc(time)))==3 %% if 3 second past
my function
break;
end
end
If you want to call my function every 3 seconds, then you should do something like this:
time=tic;
while 1
if mod((abs(toc(time))),3) == 0 %% if 3 second past
my function
end
end
Please make sure that you have some way of telling once you are done and then break the while loop.
You could set it to >= instead of ==. That will catch it if it misses the exact value.

How to run a MATLAB program for a specified time duration?

For example if there is a MATLAB program as follows:
duration = 1 % minute
i=1
while i<1000
[X,Y] = ginput(1)
i = i+1;
end
Is there any way to terminate the execution of this program or getting out of the loop when it reaches to the assigned amount of time (1 minute in this case) in such a situation in which continuation of the loop needs the user intervention (in this case clicking on any point on the plotted figure)?
If you want to do a process within your loop for a minimum of a minute, you can do it like this:
start = now
while now - start < 60/60/24
%do something for a minute
end
As a commenter above said, ginput will wait indefinitely so don't plan on that working.

MATLAB: Forcing a function to return a solution if it's taking too long

I am trying to feed 10,000 empirical data sets to a function, one after the other. The data sets are similar each time, but there are some small differences.
Usually the routine works fine, but occasionally (due to the small differences) the function will be given a data set that it will not be able to resolve, or will not be able to resolve within several hours.
I don't care that much if that data set doesn't get used. Is there some way to edit the function so it says "if this data set is too taking too long, just return some arbitrary values to the script so that we can move on"?
You can use the 'now' function to get a current datenum as you enter the function.
At some point in the function you could use it again and check the difference to see if the delta is longer than your threshold for waiting (in seconds).
starttime = now;
% processing block
if (now - starttime) > 3600
return (junk answer)
end
Within the function, call t_start = tic(); when it starts.
You can check the then check number of seconds elapsed with t_elapsed = toc(t_start);
If your function has lots of loops, you can check toc(t_start) each loop and return some error condition if the elapsed time gets too big.

Milliseconds timer matlab

I am an amateur Matlab User who is attempting to write a code to run a specific function call every 10ms for a time span of 1 second. I am having trouble trying to get something to run for the exact amount of time; I have tried to use Tic and Toc but that's in seconds (I need millisecond precision). Here is some very basic code I have been playing with to try and get readings using a function called getvelocity. Any help would be appreciated, thanks!
function [ velocity ] = Vel()
i=1;
timerID=tic;
while (toc(timerID) <=2);
[v(i)]=vpx_GetTotalVelocity;
disp (v(i));
i=i+1;
end
velocity=mean(v);
end
The code above runs for two seconds; however, I want to run in ms precision.
Assuming the function you have is fast enough (not a trivial assumption) you can achieve it like so:
tic
for t = 0.01:0.01:1 %If you want the first function call to start right away you can change this to 0:0.01:0.99
while toc < t
end
t %Put your function call here.
end
Note that 0.01 sec is 10 ms

matlab timer functions

I want to call function A in a program. This function has a for loop inside and I'd like to shorten amount of iterations but not just changing the upper limit. How could I do it in this case? I was thinking if Matlab is capable of doing something like: one timer inside a function (or maybe inside a loop) and second in the main program that calls this function? But only rough idea, I'm a beginner. Please feed back if this is good idea and how could it be implemented?
thank you!
It sounds like you're talking about having a maximum elapsed time condition in your loop, something along the lines of,
MAX_T = 10;
tic;
for n=1:NMAX
% Call your loop functions
.
.
% Break if youve spent too much time in the loop
if toc > MAX_T; break; end;
end
There are also ways of optimizing this, such as only checking the value of toc every N iterations.