Execute statements specified number of times
for index = values program statements : end
for index=values, program statements, end repeatedly executes one or more MATLAB® statements in a loop. values has one of the following forms:
increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval.
increments index by the value step on each iteration, or decrements when step is negative.
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.
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
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 the index within the loop.
To iterate over the values of a single column vector, first transpose it to create a row vector.