How to delay a loop in a function block?

4 views (last 30 days)
Mario Avila Rodriguez
Mario Avila Rodriguez on 4 Oct 2021
Answered: Paul on 5 Oct 2021
Hello everyone,
I have the next simulink model.
the function block has the following function:
function t =fcn(N)
t=0;
for i=0:1:N
t=i;
end
end
But if i add a delay of 1 second in the loop the model does not work, and it just appear a 0 on the display
function t =fcn(N)
t=0;
for i=0:1:N
t=i;
pause(1);
end
end
How can fix this in order to delay the loop for "N" seconds befor the cycle stars again.
I hope I have explained the issue clear enough.Please let me know if there is any other point that I need to clarify.
Thanks in advance!

Answers (2)

Walter Roberson
Walter Roberson on 4 Oct 2021
WIthin any one call to a MATLAB function block, you can only emit values for the "current" time.
If you were trying to create a repeating sequence, then
function t = fcn(N)
persistent state
if isempty(state); state = 0; end
if state > N
state = 0;
end
t = state;
state = state + 1;
end
This code does not rely upon N being fixed. If you change N and the next output would have been greater than N, then it resets to 0. Another design choice would be to instead reset to mod(state,N)

Paul
Paul on 5 Oct 2021
I tried this in 2019a and it worked exactly as expected. The effect of the pause(1) is to make this (simple) simulation take 12 seconds of real time for every simulation time step. For a more complex simulation it will make the execution of the Matlab Function take 12 seconds each time it's called (which I think could be simply implemented with pause(N), instead of pausing 1 second N times). When I ran the model, in Normal mode (didn't try Accelerator mode), I saw the Display block change from 0 to 12 after I counted to 12 starting when the simulation started running. Are you waiting more than 12 seconds to see the change in the Display block?

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!