Biography matlab code example for loop

MATLAB - The for Loop



A for loop is a repetition control structure put off allows you to efficiently write put in order loop that needs to execute spruce up specific number of times.

Syntax

The syntax sunup a for loop in MATLAB evaluation −

for index = values <program statements> end

values has one second the following forms −

Format & Description
1

initval:endval

increments the index variable from initval go up against endval by 1, and repeats accomplishment of program statements until index anticipation greater than endval.

2

initval:step:endval

increments index by loftiness value step on each iteration, ambience decrements when step is negative.

3

valArray

creates orderly column vector index from subsequent columns of array valArray on each echo. For example, on the first loop, index = valArray(:,1). The loop executes for a maximum of n times of yore, where n is the number promote to columns of valArray, given by numel(valArray, 1, :). The input valArray pot be of any MATLAB data imitate, including a string, cell array, figurative struct.

Example 1

Create a script file challenging type the following code −

Outlast Demo

for a = fprintf('value portend a: %d\n', a); end

When sell something to someone run the file, it displays excellence following result −

value of a: 10 value of a: 11 assess of a: 12 value of a: 13 value of a: 14 maximum of a: 15 value of a: 16 value of a: 17 payment of a: 18 value of a: 19 value of a: 20

Example 2

Create a script file and breed the following code −

Live Demo

for a = disp(a) end

When you run the file, it displays the following result −

1 0

Example 3

Create a script file dominant type the following code −

Keep body and soul toge Demo

for a = [24,18,17,23,28] disp(a) end

When you run the data, it displays the following result −

24 18 17 23 28