For-loop

The for-loop construct offers you the possibility to execute certain pieces of a program several times, while the value of certain variables is changing. A so-called loop variable keeps track of how often the program lines have to be repeated.

The general form of a for-loop is:

for loopvariable = start:step:end command lines endWhen step is omitted, a step size of 1 is used by default.

% definition of constant n n = 10; % producing an array with n rows % and 1 column, filled with zeroes A = zeros(n,1); % fill this column with values from 1 up to % n in a FOR loop for k = 1:n A(k,1) = k; end A % print the result on the screen.This loop works as follows: after the for command, the loop variable

`for k = 1:n`

means `for
`for k = 2:2:10`

means `for
% initialisation of the variable p p = 0; % run loop n times for k = 1:n p = p+1; % increase counter variable p end pIn this loop the value of

It is also possible to nest one or more for loops. By using this, you can easily fill an

% definition of the size of the matrix nr = 4; % number of rows nc = 3; % number of columns % producing an n x m matrix with nr rows % and nc columns, which is filled with zeroes. % it is not really necessary to make the matrix % beforehand and fill it with zeroes, but it is % neater, it prevents errors, and sometimes it % may be useful. A = zeros(nr,nc); % fill the matrix with random values between 0 and 1 % in a nested double FOR loop for r = 1:nr for c = 1:nc A(r,c) = rand(1); end end A

Esteur 2010-03-22