Loops

Explore loops in Python and compare them with loops in MATLAB.

Loops are used to execute a block of code repeatedly. Let’s have a look at the execution of loops in MATLAB and Python.

Press + to interact
Loops in MATLAB and Python
Loops in MATLAB and Python

The for loop

A for loop allows us to repeat a block of code a fixed number of times.

The basic syntax for a for loop in MATLAB is as follows:

Press + to interact
for i = 1:3:10 % A sequence from 1 to 10 with a step of 3
disp(i)
end
  • Line 1: We use a for loop with the iteration variable i to iterate over the array [1,4,7,10].

  • Line 2: We use the disp() command to print the iteration variable i.

Python uses the for keyword, followed by the loop variable, in keyword, and the range() function, which accepts the starting value and end value plus one. We can also tell the range() function about the step size using a third argument.

The basic syntax for a for loop in Python is as follows:

Press + to interact
for i in range(1, 11, 3): # A sequence from 1 to 10 with a step of 3
print(i)
  • Line 1: We use a for loop with the iteration variable i to iterate over the array [1,4,7,10]. Note that in the range() function, the step size of 3 is given as the third argument. In MATLAB, the step size is given in the middle of range values.

  • Line 2: We use the print() command to print the iteration variable ...