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

采纳的回答

Suman Sahu
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 个评论
Matthew Tieu
Matthew Tieu 2023-4-4
编辑:Matthew Tieu 2023-4-5
Hi S. Sahu,
Thanks for replying back. Just to make sure that I have understood your answer, does Simulink execute in a similar manner to the piece of code below?
t = 0;
while t < stop_time
% Do something and hold the current state
t = t + time_step;
end
Suman Sahu
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 CenterFile Exchange 中查找有关 Simulink Functions 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by