Uncertain about how loops behave in Simulink

5 vues (au cours des 30 derniers jours)
Matthew Tieu
Matthew Tieu le 24 Mar 2023
Modifié(e) : Suman Sahu le 5 Avr 2023
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

Réponse acceptée

Suman Sahu
Suman Sahu le 4 Avr 2023
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 commentaires
Matthew Tieu
Matthew Tieu le 4 Avr 2023
Modifié(e) : Matthew Tieu le 5 Avr 2023
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 le 5 Avr 2023
Modifié(e) : Suman Sahu le 5 Avr 2023
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by