for loop
It is a type of loop or sequence of statements executed repeatedly until exit condition is reached. Syntax :
for var = expression body end (endfor can also be used)
Example 1 : Printing numbers from 1 to 5 :
MATLAB
% the value of i will move from 1 to 5 % with an increment of 1 for i = 1:5, % displays value of i disp(i); % end the for loop end ; |
Output :
1 2 3 4 5
Example 2 : for loop with vectors :
MATLAB
% making a column vector from 1 to 10 v = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]; % the value of i will move from 1 to 10 % with an increment of 1 for i = 1:10, % modifying the value of ith element % in the column vector as v(i) * 10 v(i) = v(i) * 10; % end the for loop end ; % displays the v vector with modified values disp(v) |
Output :
10 20 30 40 50 60 70 80 90 100
Example 4 : Program to print the Fibonacci series up to 10 elements using for loop :
MATLAB
% create a row vector of 10 elements all as '1' fibonacci = ones(1, 10); % the value of i will move from 3 to 10 over the % increment of 1 for i = 3:10 % the ith term of fibonacci will computed % as the sum of its previous 2 terms fibonacci(i) = fibonacci(i - 1) + fibonacci(i - 2); % end the for loop endfor % print the fibonacci series disp(fibonacci) |
Output :
1 1 2 3 5 8 13 21 34 55
Loops (For and While) and Control Statements in Octave
Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss control statements like the if statement, for and while loops with examples.