Uncertain about how loops behave in Simulink
10 次查看(过去 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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1335039/image.png)
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 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!