27
1 MATLAB tutorial Introudction to Computation and Cognition 2015 Dr. Oren Shriki Shay Ben-Sasson, Ofer Groweiss

MATLAB tutorial (by Oren Shriki) - moodle2.bgu.ac.il data analysis, simulations, presentation of results, and more. The software runs on both UNIX and WINDOWS, on a PC or on a MAC

Embed Size (px)

Citation preview

1

MATLAB tutorial

Introudction to Computation and Cognition 2015

Dr. Oren Shriki

Shay Ben-Sasson, Ofer Groweiss

2

MATLAB is a general-purpose mathematical software that is user friendly and very useful

for data analysis, simulations, presentation of results, and more. The software runs on

both UNIX and WINDOWS, on a PC or on a MAC

MATLAB is an interpreter, which means that it performs every command line immediately

after it is entered. A script file for MATLAB is called an m-file and it must have the

extension 'm' (i.e. something like xxx.m). To run an m-file, you just enter the name of the

file without the extension at the MATLAB prompt or press F5 to save and run (when the

file is open in the editor). To evaluate a part of a MATLAB file, you mark the corresponding

lines and press F9.

Getting started

If you are a first-time user, you should run MATLAB now and follow along. The main tool

of the MATLAB is the matrix (The name MATLAB stands for 'matrix laboratory').

REMEMBER THAT: (almost) EVERYTHING IS A MATRIX IN MATLAB

A matrix of one element is called a scalar and we can create one by entering:

>> s = 3

We have just created a variable. Its name is "s", its value is three. Notice that writing s=3

results in the Command Window also writing s=3. In order to suppress the Command

Window's output, we use the ';' symbol at the end of the line:

>> s = 3;

What happens if we don't assign a variable? Writing:

>> 3 + 5

Creates a default variable called 'ans'. The resulting Command Window output will show

ans = 8, and the variable ‘ans’ will appear in the Workspace window.

3

Comments

Writing '%' symbol before anything creates a comments. Comments are ignored by the

interpreter. A multi-line comment can be created starting %{ and ending with }% (they both

have to be on a dedicated line). Try this:

% A single line comment

%{

A multi line

Comment

%}

Vectors

A matrix of one row or one column is called a vector. We can create a row vector by

entering:

>> v = [8,3,5]

Note: comma (,) differentiates between number in a row. Another way to differentiate is by

using space.

>> v = [8 3 5]

Notice the use of brackets ([ ]). In order to declare a vector or matrix, we start and end the

input with brackets.

To create a column vector we will use the ';' symbol to separate between the elements

>> u = [4.2; 5; 7]

Matrices

We can create a 3-by-3 matrix simply by entering

>> A = [3 4 0; 1 4 6; 9 7 2]

4

Note the fact that you don't have to define a variable type (“int”, “double” – for those of you

that have experience in programming languages) - you just enter it.

We can now calculate quantities like the transpose of A (AijAji)

>> A'

(the hyphen ' is a shortcut for the transpose() function)

or the transpose of v which will be a column vector:

>> v'

For example we can create another 3 by 3 matrix by entering

>> B=[v; u'; 1 0 4]

Important to note: Matlab is strict about dimensional matching.

>> B=[v'; u; 1 0 4] would produce a common error:

Error using horzcat

Dimensions of matrices being concatenated are not consistent.

If we have several matrices, we can add them

>> A+B

or multiply them

>> A*B

but we have to take care that the dimensions are appropriate. The multiplication operation

we just used obeys the rules of ordinary matrix multiplication. There is another kind of

multiplication, which is multiplying each element in a matrix by the corresponding element

in another matrix which has to be the same size (this is called array multiplication or

element-by-element multiplication). To do this you enter

5

>> A.*B

This dot rule is general, so if you enter

>> A.^2

it will raise all the elements of A to the power of 2 (which is of course different from A^2,

which is A*A).

Functions

MATLAB has some commands/functions for the construction of special matrices.

Some functions require parameter (input) and return a value (output). Functions are like

mini scripts/programs that perform a designated action.

The function 'ones' creates a vector or matrix filled with ones (1). The amount of ones is

defined by the parameters, which are received as input inside parenthesis.

>> ones(3,4)

will create a matrix of 1's with 3 rows and 4 columns.

Q1: there is no 'twos' or 'threes' function, why is this?

You can figure out what

>> zeros(5,7)

does.

To create an identity matrix of order 5 you type

>> eye(5)

6

Size() and Length()

What if we wanted to know the size of a matrix that is stored in the variable A. Let’s try:

>> size(A)

We get a 3-by-3, 3 rows and 3 columns (on 2d matrix - the first dimension is always rows and then

the 2nd dimension is columns).

>> size(A’)

We got the same result, a 3-by-3.

>> C = [10 15]

Can you guess what are the dimensions of the matrix C (yes I know it’s a vector, But everything in

MATLAB is a _____)? Run size(C) to verify your answer.

We get a vector result of [1 2], we have 1 row and 2 columns – so C is a column vector, right?

No, it’s a bit confusing, it’s a row vector, we have a single row with element values.

>> size(C’)

C’ is just transpose(C), hence, the transpose of C which equals [10;15], this is a column vector and

the result of size(C’) is [2 1].

The function length just outputs the value of the dimension with the maximum value, in our case

it’s 2:

>> length(C)

Defining a range of numbers

If you type

>> x=1:10

This will give a vector with all the integer numbers from 1 to 10, and

>> y=0:0.1:8

will give a vector of all the numbers between 0 and 8 with a 0.1 step.

Note the use of the ':' symbol. It represents range, starting number (left), step size (middle)

and ending number (right). By default, Matlab treats 1:10 as 1:1:10, meaning the step size

is 1.

7

The number of elements in a vector is determined by the step, in order to have a fixed

number of elements we use the linspace function:

>> z = linspace(1,100,5)

This will create a vector containing 5 elements, the first is 1, the last is 100, and the step

size is determined by the number of elements.

Using the help

If you would like to learn about the syntax and the different uses of a command just type

'help' and the name of the command. For example try this:

>> help rand

A quicker way to use the Matlab internal help is:

>> doc rand

This will just ‘output’ a summary of the function help in the ‘Command Window’

8

If you want to search for commands related to some topic, say complex numbers, you

enter

>> lookfor complex

(Most of the times you need help, just use ‘google.com’, it a brand new company that has

a great search engine, you should try it out).

Indices:

Scalars, vectors and matrices are in fact just matrices (remember the mantra:

EVERTHING IN MATLAB IS A MATRIX). A scalar is matrix of order 1X1, and a vector is

matrix of order 1XN or NX1.

Indices are "pointers" (don’t be confused with pointers in other programming languages) to

locations inside a matrix. In Matlab they are called ‘logicals’ (we will learn what that

means later).

In order to access an element inside a matrix, we must tell Matlab which row/s and/or

column/s we would like to access. The order is ALWAYS rows, then columns.

To access the first element in vector u, we will call:

>> u(1,1) %access the value in row 1 column 1 in the vector u

After we created a matrix we might want to extract some elements from it. To extract the

i'th element of a vector you type

>> v(1,i) %assuming v is a row vector

or

>> v(i)

Typing the command ‘A(i, j)’ will extract the element of A that sits in the i'th row in the j'th

column. For example:

>> A(2,3)

9

will extract the element in the 2nd row in the 3rd column.

Typing the command:

>> A(:,1:2)

will extract the first 2 columns of A.

When do we use just 'i' and when do we use 'i' and 'j'?

Vectors can receive just 'i' because there's only one dimension. When accessing an

element in a matrix it's common to use both 'i' and 'j' (although it's not mandatory).

Suppose we want to know the sum of the 3rd row. We will use the colon (:) and the

function sum like this:

>> sum(A(3,:))

for the sum of the third column we would type:

>> sum(A(:,3))

Conditionals

Now, type the following command:

>> A>3

What you got is a new matrix, with ones and zeros. Every place with one means that the

corresponding entry in A fulfills the condition (bigger than 3). Zeros means that the

opposite is true, that is, the number is smaller or equal to 3. We now go further by typing:

>> (A>3) .* A

can you explain the result ?

10

hint: notice we used the element by element multiplier (.*)

Operator precedence

Try this and explain the result:

>> A.*A > 5*A

What runs first? The element-wise multiplication of the > operator or the * matrix

multiplication:

http://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html

See the list here, it’s ordered from the highest precedence to the lowest precedence. In

our example, the ‘.*’ expression is first evaluated, than the ‘*’ expression and only than the

‘>’ because of its relative lower precedence.

More general functions and commands

Until this stage, every result was displayed on the screen. If you don't want to see the

result, just add a ';' at the end of the command. You can use the ';' also to separate

different commands on the same line like this

>> x=3; y=[1 x ones(1,5); 5*rand(1,7); 1:7];

Try it and then type

>> y

to see what we got.

While working with MATLAB, you can always list the variables in the workspace by

entering 'who' or 'whos' ('whos' shows also the size of the variables)

To log everything you type in the workspace (and the results), use the 'diary' command.

To start, enter something like:

>> diary my_log.txt

and to stop saving, enter:

11

>> diary off

Type 'help diary' to see exactly what it does.

diff function:

The function diff(v) receives an input a vector v of n element and returns a vector of (n-1)

elements. For each two adjacent elements in v, diff calculates the difference between

them. For example, if u = diff(v), then u(1) = v(2)-v(1), u(2) = v(3)-v(2), etc.

find function:

find is a very useful function that can be very tricky. The function finds the indices of all

non zero elements in a matrix. Say we have vector v = [2,0,7], then find(v) returns [1,3].

Now say we want to find the locations of elements equal to a certain number (for example,

the number 7), this can be done with find(v==7). To understand how this works, let's break

down the steps: v==7 is a logical statement, it creates a logical matrix the same size as v,

where every element in index i is the answer to the clause 'if v(i) == 7'. The output of v==7

in our example will be [0,0,1], because only the third element is in fact 7. This is why the

output of find(v==7) will be 3. In vectors, this function usually returns the desired output,

but in matrices it can be tricky.

More practice

Sum, transpose, and diag

You're probably already aware that the special properties of a magic square have to do

with the various ways of summing its elements. If you take the sum along any row or

column, or along either of the two main diagonals, you will always get the same number.

Let's verify that using MATLAB. The first statement to try is

sum(A)

MATLAB replies with

ans =

34 34 34 34

12

When you don't specify an output variable, MATLAB uses the variable ans, short for

answer, to store the results of a calculation. You have computed a row vector containing

the sums of the columns of A. Sure enough, each of the columns has the same sum, the

magic sum, 34.

How about the row sums? MATLAB has a preference for working with the columns of a

matrix, so the easiest way to get the row sums is to transpose the matrix, compute the

column sums of the transpose, and then transpose the result. The transpose operation is

denoted by an apostrophe or single quote, '. It flips a matrix about its main diagonal and it

turns a row vector into a column vector. So

A'

Produces:ans =

16 5 9 4

3 10 6 15

2 11 7 14

13 8 12 1

And

sum(A')'

produces a column vector containing the row sums

ans =

34

34

34

34

The sum of the elements on the main diagonal is easily obtained with the help of the diag

function, which picks off that diagonal.

diag(A)

produces

ans =

16

10

13

7

1

and

sum(diag(A))

produces

ans =

34

The other diagonal, the so-called antidiagonal, is not so important mathematically, so

MATLAB does not have a ready-made function for it. But a function originally intended for

use in graphics, fliplr, flips a matrix from left to right.

sum(diag(fliplr(A)))

ans =

34

You have verified that the matrix in Dürer's engraving is indeed a magic square and, in the

process, have sampled a few MATLAB matrix operations. The following sections continue

to use this matrix to illustrate additional MATLAB capabilities.

Subscripts

The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the

number in the fourth row and second column. For our magic square, A(4,2) is 15. So it is

possible to compute the sum of the elements in the fourth column of A by typing

A(1,4) + A(2,4) + A(3,4) + A(4,4)

This produces

ans =

34

but is not the most elegant way of summing a single column.

It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is

the usual way of referencing row and column vectors. But it can also apply to a fully two-

dimensional matrix, in which case the array is regarded as one long column vector formed

14

from the columns of the original matrix. So, for our magic square, A(8) is another way of

referring to the value 15 stored in A(4,2).

If you try to use the value of an element outside of the matrix, it is an error:

t = A(4,5)

Index exceeds matrix dimensions.

On the other hand, if you store a value in an element outside of the matrix, the size

increases to accommodate the newcomer:

X = A;

X(4,5) = 17

X =

16 3 2 13 0

5 10 11 8 0

9 6 7 12 0

4 15 14 1 17

The Colon Operator

The colon, :, is one of MATLAB's most important operators. It occurs in several different

forms. The expression

1:10

is a row vector containing the integers from 1 to 10

1 2 3 4 5 6 7 8 9 10

To obtain nonunit spacing, specify an increment. For example

100:-7:50

is

100 93 86 79 72 65 58 51

and

0:pi/4:pi

is

15

0 0.7854 1.5708 2.3562 3.1416

Subscript expressions involving colons refer to portions of a matrix.

A(1:k,j)

is the first k elements of the jth column of A. So

sum(A(1:4,4))

computes the sum of the fourth column. But there is a better way. The colon by itself

refers to all the elements in a row or column of a matrix and the keyword end refers to the

last row or column. So

sum(A(:,end))

computes the sum of the elements in the last column of A.

ans =

34

Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are

sorted into four groups with equal sums, that sum must be

sum(1:16)/4

which, of course, is

ans =

34

Arrays

When they are taken away from the world of linear algebra, matrices become two-

dimensional numeric arrays. Arithmetic operations on arrays are done element-by-

element. This means that addition and subtraction are the same for arrays and matrices,

but that multiplicative operations are different. MATLAB uses a dot, or decimal point, as

part of the notation for multiplicative array operations.

The list of operators includes:

+ Addition

- Subtraction

16

.* Element-by-element multiplication

./ Element-by-element division

.\ Element-by-element left division

.^ Element-by-element power

.' Unconjugated array transpose

If the Dürer magic square is multiplied by itself with array multiplication

A.*A

the result is an array containing the squares of the integers from 1 to 16, in an unusual

order.

ans =

256 9 4 169

25 100 121 64

81 36 49 144

16 225 196 1

Array operations are useful for building tables. Suppose n is the column vector:

n = (0:9)';

Then

pows = [n n.^2 2.^n]

builds a table of squares and powers of two.

pows =

0 0 1

1 1 2

2 4 4

3 9 8

4 16 16

5 25 32

6 36 64

7 49 128

17

8 64 256

9 81 512

The elementary math functions operate on arrays element by element. So

format short g

x = (1:0.1:2)';

logs = [x log10(x)]

builds a table of logarithms.

logs =

1.0 0

1.9 0.27875

2.0 0.30103

Multivariate Data

MATLAB uses column-oriented analysis for multivariate statistical data. Each column in a

data set represents a variable and each row an observation. The (i,j)th element is the ith

observation of the jth variable.

As an example, consider a data set with three variables:

Heart rate

Weight

Hours of exercise per week

For five observations, the resulting array might look like:

D =

72 134 3.2

81 201 3.5

69 156 7.1

82 148 2.4

75 170 1.2

18

The first row contains the heart rate, weight, and exercise hours for patient 1, the second

row contains the data for patient 2, and so on. Now you can apply many of MATLAB's

data analysis functions to this data set. For example, to obtain the mean and standard

deviation of each column:

mu = mean(D), sigma = std(D)

mu =

75.8 161.8 3.48

sigma =

5.6303 25.499 2.2107

For a list of the data analysis functions available in MATLAB, type

help datafun

If you have access to the Statistics Toolbox, type

help stats

Scalar Expansion

Matrices and scalars can be combined in several different ways. For example, a scalar is

subtracted from a matrix by subtracting it from each element. The average value of the

elements in our magic square is 8.5, so

B = A - 8.5

forms a matrix whose column sums are zero.

B =

7.5 -5.5 -6.5 4.5

-3.5 1.5 2.5 -0.5

0.5 -2.5 -1.5 3.5

-4.5 6.5 5.5 -7.5

sum(B)

ans =

0 0 0 0

19

With scalar expansion, MATLAB assigns a specified scalar to all indices in a range. For

example:

B(1:2,2:3) = 0

zeros out a portion of B

B =

7.5 0 0 4.5

-3.5 0 0 -0.5

0.5 -2.5 -1.5 3.5

-4.5 6.5 5.5 -7.5

Logical Subscripting

The logical vectors created from logical and relational operations can be used to reference

subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the

result of some logical operation. Then X(L) specifies the elements of X where the

elements of L are nonzero.

This kind of subscripting can be done in one step by specifying the logical operation as the

subscripting expression. Suppose you have the following set of data.

x =

2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8

The NaN is a marker for a missing observation, such as a failure to respond to an item on

a questionnaire. To remove the missing data with logical indexing, use finite(x), which is

true for all finite numerical values and false for NaN and Inf.

x = x(finite(x))

x =

2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8

Now there is one observation, 5.1, which seems to be very different from the others. It is

an outlier. The following statement removes outliers, in this case those elements more

than three standard deviations from the mean.

x = x(abs(x-mean(x)) <= 3*std(x))

x =

2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8

20

For another example, highlight the location of the prime numbers in Dürer's magic square

by using logical indexing and scalar expansion to set the nonprimes to 0.

A(~isprime(A)) = 0

A =

0 3 2 13

5 0 11 0

0 0 7 0

0 0 0 0

The find Function

The find function determines the indices of array elements that meet a given logical

condition. In its simplest form, find returns a column vector of indices. Transpose that

vector to obtain a row vector of indices. For example

k = find(isprime(A))'

picks out the locations, using one-dimensional indexing, of the primes in the magic

square.

k =

2 5 9 10 11 13

Display those primes, as a row vector in the order determined by k, with

A(k)

ans =

5 3 2 11 7 13

When you use k as a left-hand-side index in an assignment statement, the matrix structure

is preserved.

A(k) = NaN

A =

16 NaN NaN NaN

NaN 10 NaN 8

21

9 6 NaN 12

4 15 14 1

Graphics and Visualization

MATLAB is indeed a great tool for visualization of data of all sorts. The first command you

should learn how to use is the 'plot'. If you want to plot vector y versus vector x just type

>> plot(x,y(

MATLAB will produce a figure window and will plot the graph.

For example, type the following:

>> x = 0:0.01:pi*4

>> plot(x, sin(x))

To learn more about the 'plot' command, try the help on it. To present several plots on the

same figure, use the 'subplot' command. To create another figure window, use the 'figure'

command.

Now, we shall learn about a useful command: ‘hist’. With ‘hist’ you get nice histograms

very quickly. Try this:

>> x = rand(1000,1) ;

this will create a vector with 1000 elements and store it in x.

>> max(x)

this is the greatest element

>> max(x) – min(x)

this is the difference between the greatest and lowest

>> hist(x)

what did you get ? try this:

>> y = rand(1000,1)

>> hist (x+y)

22

this is the same idea

>> plot(x, y, ‘.’)

>> title(‘A big mess’)

>> xlabel(‘vector x’)

>> ylabel(‘vector y’)

remember that every Matlab function (even those you will write) has input arguments and

output arguments . The input arguments are what you put between the brackets, for

example in plot(x,y) x and y are the inputs. The output is what you get back from the

function. For example in m = max(x) the result of the max function is placed in m.

The variables you use to get the output are the glue between the various commands.

In order to find about the input and output of functions, simply type the magic word ‘help’.

The following commands will help you control the way your graphs look: axis, xlabel,

ylabel, title, hold, grid, get, set, gca, gcf

Here is a list of some specialized 2-D functions:

bar - creates a bar graph

errorbar - creates a plot with error bars

The best way to learn about MATLAB visualization capabilities is to see the demo and

then learn about the commands that are most useful for you. Note that the demos are

written in MATLAB so you can "type" the files and just copy the commands you need.

To type a file inside MATLAB's workspace you enter for example

>> type lorenz.m

This program plots the orbit around the Lorenz chaotic attractor. If

you want to run it just type

>> lorenz

23

Data Analysis

Here we list few functions, which are very useful for data analysis:

max - maximum value

min - minimum value

mean - mean value

median - median value

std - standard deviation

sort – sorting

sum -sum of the elements

prod - product of elements

cumsum - cumulative sum of elements

cumprod - cumulative product of elements

diff - approximate derivatives

corrcoef - correlation coefficients

cov - covariance matrix

For vector arguments, it does not matter whether the vectors are oriented in a row or

column direction. For array arguments, the functions operate in a column-oriented fashion

on the data in the array. This means, for example, that if you apply 'max' to an array,

the result is a row vector containing the maximum values over each column. If A is a

matrix and you want the maximal element just type

>> max(max(A))

Typing help on each of these functions will give you the full description of them. Note that,

although it is very easy to write most of these functions yourself, it is nice to already have

them and it makes the scripts more compact.

24

Loops and Clauses

Sometimes we would like to perform an operation multiple times, or perform only certain

operations if certain condition are met.

IF clause

A clause is a statement that has Boolean value, either true or false. Clauses rely on the

understanding of logical “if A, then B”. A clause is identified by the word ‘if’. Here is an

example.

>> A = [1,2]

We want to add a third number, if and only if, the second element in A is 2.

>> if A(2)==2

A(3) = 3;

end

When writing ‘if’ in the command window, pressing the enter key will not run the program

just yet. The clause if has a scope – the range in which the if applies. We identify where

the scope ends by the command ‘end’. Every ‘if’ has an end.

What we did in the example is ask a question – “is the second element of A equal to 2?” if

indeed the answer is yes, then we add a three, and if not, we do nothing.

ELSE

Everything that doesn’t fall under the ‘if’ condition, falls under ‘else’. In our previous

example, let’s change the value of the second element in A if it is not 2:

>> if A(2)==2

A(3) = 3;

else

A(2) = 2;

end

What happens if we don’t specify an else condition? Matlab creates one but does nothing,

this is invisible to the user.

Another way to differentiate between condition is to use ‘elseif’. This clause means that

the ‘if’ condition isn’t met but we have another condition:

25

>> if A(2)==2

A(3) = 3;

elseif A(1)==1

A(3) = 3;

else

A(2) = 2;

end

We expanded our conditions and now we want to add a 3 even if the second element isn’t

2 but the first is 1.

Logical operators:

In the last example we made a redundant step. Instead of asking ‘if’ and then ‘elseif’, we

can combine the two condition using OR. Remember, in logic A or B means that at least

one of the statements needs to be true.

Logical operators symbols: & (and), | (or, Shift+\), ~ (not)

So in order to write the previous example we use |:

>> if A(2)==2 || A(1)==1

A(3) = 3;

else

A(2) = 2;

end

Why did we use two | symbols? It’s more efficient. A double ‘or’ symbol doesn’t check the

second condition if the first is true. A double ‘and’ symbol doesn’t check the second

condition if the first is false.

More examples:

>> if A(2)==2 && A(1)==1

A(3) = 3;

end

Here we will only perform the A(3)=3 operation only if both clauses are met.

>> if ~(A(2)==2 )

A(3) = 3;

end

This is the exact opposite of the first example using the not operator.

26

While loop

One thing that we would like to avoid while programming is “hard-coding”. This means

writing down exactly what we want the code to do. So what we do if we want to perform

100 operation? we can hard code at least 100 lines of code, but this is redundant.

We can use a loop to perform similar operation in a sequential manner (one after the

other).

A while loop is an ‘if’ clause that is repeated as long as the ‘if’ is true. Every repeating step

is called an iteration.

We can use this in order to have timed-loops, meaning a loop that runs for a given time.

The functions ‘tic’ and ‘toc’ are like the buttons on a stopwatch. ‘tic’ starts the timer and

and ‘toc’ measures how much passed this the last ‘tic’ (‘toc’ can be called multiple times,

like the ‘lap’ button on a stopwatch). An example for a timed loop:

>> tic;

>> while toc<3

756+1

end

This example runs for 3 seconds and prints ‘757’ in every iteration. What happens after 3

seconds? toc<3 is false, and therefore the loop stops.

A very common while-loop is a counter loop, that sequentially iterates for a known number

of steps. If we wanted to print every element in a vector v, we can do the following:

>> v = 1:10;

>> counter = 1;

>> while counter <= length(v)

v(counter)

counter = counter + 1;

end

Once the counter is raised to 11, the loop breaks.

This loop was so common that it we actually shortened for easier use, and not it’s called:

For loops:

A for loop that operates the same the last example, is written as follows:

>> for i = 1:length(v)

v(i)

end

27

Where is a the ‘i=i+1’? it is done in the background, invisible to the user.

A for loop iterates over a vector, in the last example, that vector is 1:length(v). We have to

create a for loop variable, in the last example that variable is ‘i’ (short for index) – we

should never change i inside the loop – trust the loop, it will increase i in every iteration.

Uses:

When should we for and when should we use while?

A for loop is used if we know exactly how many iteration are needed.

A while loop is used if we don’t know the number of iterations.

As a rule, while loops can do everything a for loop does, them why use for loops? First,

they’re short and accessible, but the main reason is that for loops will not perform infinite

iterations.

An infinite loop is a loop that never stops. A while loop that’s not correctly configured will

iterate forever. Here’s an example:

>> counter = 1;

>> while counter <= length(v)

v(counter)

end

What’s wrong? We forgot to write ‘counter = counter + 1;’, meaning counter never

increases and therefore is always <=length(v).

To stop an infinite loop (or any script) press ctrl+c or ctrl+break in the command window.