How to delay a loop in a function block?

조회 수: 19 (최근 30일)
Mario Avila Rodriguez
Mario Avila Rodriguez 2021년 10월 4일
답변: Paul 2021년 10월 5일
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