How to delay a loop in a function block?

17 次查看(过去 30 天)
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!

回答(2 个)

Walter Roberson
Walter Roberson 2021-10-4
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 2021-10-5
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?

类别

Help CenterFile Exchange 中查找有关 General Applications 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by