Uncertain about how loops behave in Simulink
조회 수: 2 (최근 30일)
이전 댓글 표시
To whom it may concern,
I have been experimenting with while loops and for loops to understand how loops work in block code. In Simulink, I have created a for loop to add all numbers from 1 to 20 together as shown in the image below. The for loop is set to reset the states of any variables per iteration. Even though the code gives me the correct result, I notice that the scope shows a straight line rather than a sawtooth wave (like expected).
From the scope, I was thinking that the for loop just runs too quickly to see the sawtooth wave. Since I would like clarification about the behaviour of loops and while loops in Simulink, I have a question. Do for loops and while loops just run once in the Simulink program? Thanks in advance.
Regards
Matthew
댓글 수: 0
채택된 답변
Suman Sahu
2023년 4월 4일
Hello Matthew,
In Simulink, for and while iterator blocks, just like other blocks update their states at each simulation timestep.
Hence when the iterator blocks update their states, the for and while loops execute entirely at each simulation timestep and same output is generated everytime because of the constant input which results in a straight line plot.
Hope it clears your doubts.
댓글 수: 2
Suman Sahu
2023년 4월 5일
편집: Suman Sahu
2023년 4월 5일
Hi Matthew,
Yes, the simulation runs while the stop time is not reached. The time step may be fixed or variable depending on the solver type.
As for the execution of the loops, the termination condition for while or for loops is not the simulation time. It depends on the Number of Iterations input to the loop. What happens is that at each time step, say 0, 0.2, 0.4 etc, the loop blocks have to update their states which means the loop executes each time to completion. For instance, you have number of iterations input as 20, so the following loop executes to termination at each time step:
n = 20; %number of iterations input
while i < n
%do something, add in you case
i = i + 1;
end
Only when the loop execution is complete and block states are updated, the simulation moves to the next time step and same execution happens as input remains the same.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Simulink Functions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!