for loops

for loops are usually designed to be repreated a prescribed number of times. See while loops for the alternative looping structure

The generic format is

for index = list_of_values

    %  loop body consists of statements to be repeated
    
end

Simple loop

for i = 1:10
  fprintf('%3d  %6d\n',i,i^2)
end

Traverse a vector

x = rand(8,1);
for i = 1:length(x)
  fprinf('%3d  %8.5f\n',i,x(i))
end

Traverse a sequence

for v = [-3*pi  0  pi  2*pi]
  fprinf('%8.5f\n',v)        %  v is a scalar, there is no loop counter
end

Document updated 2016-10-10.

Go back to the Reference page.