examples of for loop in matlab

0

for loop to repeat specified number of time

 

for  index= values

   statements 

end

 

executes a group of statements in a loop for a specified number of times. values has one of the following forms:

 

initVal:endVal — Increment the index variable from initVal to endVal by 1, and repeat execution of statements until index is greater than endVal.

 

initVal:step:endVal — Increment index by the value step on each iteration, or decrements index when step is negative.

 

valArray — Create a column vector, index, from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes a maximum of n times, where n is the number of columns of valArray, given by numel(valArray(1,:)). The input valArray can be of any MATLAB data type, including a character vector, cell array, or struct.

All Contributions

for v = [1 5 8 17]
   disp(v)
end

This code display :

     1

 

     5

 

     8

 

    17

Step by increments of -0.2, and display the values.

 

for v = 1.0:-0.2:0.0
   disp(v)
end

Create a Hilbert matrix of order 10.

s = 10;
H = zeros(s);

for c = 1:s
    for r = 1:s
        H(r,c) = 1/(r+c-1);
    end
end

total contributions (3)

New to examplegeek.com?

Join us