본문 바로가기

Enginius/Matlab

for loop

for -Execute statements specified number of times

Syntax

for index = values
   program statements
          :
end

Description

for index=valuesprogram statements, end repeatedly executes one or more MATLAB statements in a loop. values has one of the following forms:

initval:endval

increments the index variable from initval to endval by 1, and repeats execution ofprogram statements until index is greater than endval.

initval:step:endval

increments index by the value step on each iteration, or decrements when step is negative.

valArray

creates 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 for 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 string, cell array, or struct.

Tips

  • To force an immediate exit of the loop, use a break or return statement. To skip the rest of the instructions in the loop, increment the loop counter, and begin the next iteration, use a continue statement.

  • Avoid assigning a value to the index variable within the body of a loop. The for statement overrides any changes made to theindex within the loop.

  • To iterate over the values of a single column vector, first transpose it to create a row vector.

Examples

Create a Hilbert matrix using nested for loops:

k = 10;
hilbert = zeros(k,k);      % Preallocate matrix

for m = 1:k
    for n = 1:k
        hilbert(m,n) = 1/(m+n -1);
    end
end
 

Step by increments of -0.1, and display the step values:

for s = 1.0: -0.1: 0.0
   disp(s)
end
 

Execute statements for a defined set of index values:

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

Successively set e to unit vectors:

for e = eye(5)
  disp('Current value of e:')
  disp(e)
end

See Also

break | colon | continue | end | if | parfor | return | switch | while

'Enginius > Matlab' 카테고리의 다른 글

subplot  (0) 2011.10.25
clear all / close all / clc / clf  (2) 2011.10.25
normrnd (White Gaussian Noise sampling)  (0) 2011.10.25
plot  (0) 2011.10.13
classify, knnclassify  (0) 2011.10.13