Vous êtes sur la page 1sur 46

Matlab brief tutorial

Table of Contents
Introductory concepts ........................................................................................................... 1
Matrix generation ................................................................................................................ 4
Matrix operations ................................................................................................................ 9
Array indexing .................................................................................................................. 14
Workspace ........................................................................................................................ 22
Strings ............................................................................................................................. 22
Functions ......................................................................................................................... 23
Plots ................................................................................................................................ 24
Scripting .......................................................................................................................... 37
Loops and conditional statements ......................................................................................... 39
Final hint ......................................................................................................................... 45

Introductory Matlab script by Giulio Coluccia (giulio.coluccia@polito.it) Main source: Matlab Quick Start Guide by
Mathworks http://www.mathworks.it/help/techdoc/learn_matlab/bta3so7.html

An up-to-date primer to Matlab is available here: http://www.mathworks.it/help/pdf_doc/matlab/getstart.pdf

Introductory concepts
Matlab is a suite for Numerical Analysis . Its capabilities can be expanded by using Toolboxes (e.g. for
Symbolic Analysis). This means that each variable must be assigned a value:

a = 5 % Generate a variable called 'a' and assign it a value of 5

a % Ask for a's value

a =

a =

Matlab is an interpreted language. This means that there is no need to compile. Errors are discovered at
runtime. E.g. let's ask the value of variable b

This generates an error

% b

Let's define it

b = 3

1
Matlab brief tutorial

b =

Usual operators have usual purposes...

c = a+b
d = a/b

c =

d =

1.6667

as usual mathematatical functions

e = sin(c)
f = sin(d)

e =

0.9894

f =

0.9954

if no output variable is specified, Malab creates the variable ans for you

a*b

ans =

15

To suppress the output of a command on screen, use ;

e = a-b;

i and j denote complex unit = sqrt(-1). It's better not to use them for naming variables.

z = a+j*b
y = c+i*d

2
Matlab brief tutorial

real(z), imag(y), abs(z), angle(y)

z =

5.0000 + 3.0000i

y =

8.0000 + 1.6667i

ans =

ans =

1.6667

ans =

5.8310

ans =

0.2054

Matlab knows a certain number of constants

pi
eps
Inf
NaN

ans =

3.1416

ans =

2.2204e-16

ans =

Inf

3
Matlab brief tutorial

ans =

NaN

Variables can have any alphanumerical name starting with a letter. Matlab is case sensitive

abc123 = 6;

This exists

abc123

abc123 =

This one doesn't and generates an error

% Abc123

Up and down arrows can be used to recall previously issued commands. If you press them after typing,
only commands in history beginning with what you typed will be shown.

Matrix generation
Matlab is optimized for matrix calculations. Actually, scalars are treated as 1x1 matrices, column vectors
as Nx1 matrices and row vectors as 1xN matrices.

Matlab can also work with multi-dimensional matrices, i.e. matrices with D>2 dimensions.

Matrices can be created:

1. Manually inserting its elements

2. From built-in functions

3. From M-files (later)

4. Loaded from external data files (later)

Let's create a 3x3 matrix. Matrices are enclosed by square brackets. Space or , separate elements in a row.
; separates rows from each other

A = [1 2 3; 4 5 6; 7, 8, 9]

A =

1 2 3
4 5 6
7 8 9

4
Matlab brief tutorial

Row vector

B = [4 5 6]

B =

4 5 6

Column vector

C = [7;8;9]

C =

7
8
9

Let's create a 2x3 matrix of zeros

zeri = zeros(2,3)

zeri =

0 0 0
0 0 0

What is |zeros|? Let's ask for help

help zeros

ZEROS Zeros array.


ZEROS(N) is an N-by-N matrix of zeros.

ZEROS(M,N) or ZEROS([M,N]) is an M-by-N matrix of zeros.

ZEROS(M,N,P,...) or ZEROS([M N P ...]) is an M-by-N-by-P-by-... array o


zeros.

ZEROS(SIZE(A)) is the same size as A and all zeros.

ZEROS with no arguments is the scalar 0.

ZEROS(..., CLASSNAME) is an array of zeros of class specified by the


string CLASSNAME.

ZEROS(..., 'like', Y) is an array of zeros with the same data type, spa
and complexity (real or complex) as the numeric variable Y.

Note: The size inputs M, N, and P... should be nonnegative integers.

5
Matlab brief tutorial

Negative integers are treated as 0.

Example:
x = zeros(2,3,'int8');

See also EYE, ONES.

Overloaded methods:
distributed/zeros
codistributor2dbc/zeros
codistributor1d/zeros
codistributed/zeros
gpuArray/zeros

Reference page in Help browser


doc zeros

Let's create a 4x4 matrix of uniformly distributed elements

unif1 = rand(4,4)

unif1 =

0.4995 0.3383 0.3761 0.9319


0.6434 0.5756 0.2587 0.0235
0.8723 0.8703 0.7623 0.6562
0.1314 0.1272 0.5571 0.6566

but also

unif2 = rand(4)

unif2 =

0.8729 0.2509 0.7414 0.5307


0.9315 0.2515 0.2400 0.7222
0.8860 0.6849 0.4127 0.0580
0.4591 0.2608 0.8285 0.0926

because matlab functions can have different syntaxes

help rand

RAND Uniformly distributed pseudorandom numbers.


R = RAND(N) returns an N-by-N matrix containing pseudorandom values dra
from the standard uniform distribution on the open interval(0,1). RAND
or RAND([M,N]) returns an M-by-N matrix. RAND(M,N,P,...) or
RAND([M,N,P,...]) returns an M-by-N-by-P-by-... array. RAND returns a
scalar. RAND(SIZE(A)) returns an array the same size as A.

Note: The size inputs M, N, P, ... should be nonnegative integers.

6
Matlab brief tutorial

Negative integers are treated as 0.

R = RAND(..., CLASSNAME) returns an array of uniform values of the


specified class. CLASSNAME can be 'double' or 'single'.

R = RAND(..., 'like', Y) returns an array of uniform values of the


same class as Y.

The sequence of numbers produced by RAND is determined by the settings


the uniform random number generator that underlies RAND, RANDI, and RAN
Control that shared random number generator using RNG.

Examples:

Example 1: Generate values from the uniform distribution on the


interval [a, b].
r = a + (b-a).*rand(100,1);

Example 2: Use the RANDI function, instead of RAND, to generate


integer values from the uniform distribution on the set 1:100.
r = randi(100,1,5);

Example 3: Reset the random number generator used by RAND, RANDI, an


RANDN to its default startup settings, so that RAND produces the sam
random numbers as if you restarted MATLAB.
rng('default')
rand(1,5)

Example 4: Save the settings for the random number generator used by
RAND, RANDI, and RANDN, generate 5 values from RAND, restore the
settings, and repeat those values.
s = rng
u1 = rand(1,5)
rng(s);
u2 = rand(1,5) % contains exactly the same values as u1

Example 5: Reinitialize the random number generator used by RAND,


RANDI, and RANDN with a seed based on the current time. RAND will
return different values each time you do this. NOTE: It is usually
not necessary to do this more than once per MATLAB session.
rng('shuffle');
rand(1,5)

See <a href="matlab:helpview([docroot '\techdoc\math\math.map'],'update


RAND with the 'seed', 'state', or 'twister' inputs.

See also RANDI, RANDN, RNG, RANDSTREAM, RANDSTREAM/RAND,


SPRAND, SPRANDN, RANDPERM.

Overloaded methods:
RandStream/rand
distributed/rand
codistributor2dbc/rand
codistributor1d/rand

7
Matlab brief tutorial

codistributed/rand
gpuArray/rand

Reference page in Help browser


doc rand

other useful matrix building functions: randn, eye, ones

generate the empty matrix

Aempty = []

Aempty =

[]

generate "range" vectors with : 1 to 20

a1to20 = 1:20

a1to20 =

Columns 1 through 13

1 2 3 4 5 6 7 8 9 10 11 12

Columns 14 through 20

14 15 16 17 18 19 20

1 to 20 with step size of 2

a1to20step2 = 1:2:20

a1to20step2 =

1 3 5 7 9 11 13 15 17 19

steps can be negative

a20to1stepNeg = 20:-1:1

a20to1stepNeg =

Columns 1 through 13

20 19 18 17 16 15 14 13 12 11 10 9

8
Matlab brief tutorial

Columns 14 through 20

7 6 5 4 3 2 1

Matrix operations
Matlab allows to process all the elements of a matrix as a whole

a = randn(3,4)
a + 5
sin(a)

a =

-0.8380 -0.1900 -0.0787 -1.7703


-1.1438 0.4207 -1.3214 0.7532
-2.2245 0.7608 0.3525 -0.8529

ans =

4.1620 4.8100 4.9213 3.2297


3.8562 5.4207 3.6786 5.7532
2.7755 5.7608 5.3525 4.1471

ans =

-0.7433 -0.1888 -0.0786 -0.9802


-0.9102 0.4084 -0.9691 0.6839
-0.7938 0.6895 0.3453 -0.7532

+ and - perform matrix sum and subtraction

b = randn(3,4)
c = a+b
d = a-b

b =

0.9724 -1.0063 -1.3667 1.4398


-1.0553 -1.1227 0.7456 0.6397
-1.0872 -1.5828 -0.9520 -1.0355

c =

0.1344 -1.1962 -1.4454 -0.3306


-2.1992 -0.7020 -0.5759 1.3929
-3.3118 -0.8219 -0.5995 -1.8884

9
Matlab brief tutorial

d =

-1.8104 0.8163 1.2881 -3.2101


-0.0885 1.5434 -2.0670 0.1134
-1.1373 2.3436 1.3045 0.1825

dimensions must be compliant

e = ones(4,2);

This generates an error

% f = a+e

* performs matrix product (row-column product)

f = b*e

f =

0.0392 0.0392
-0.7928 -0.7928
-4.6575 -4.6575

dimensions must be compliant. This generates an error

% g = a*b

\ perform "matrix left division", which is the solution to Ax = B, with A square and invertible and x =
A(^-1)*B = A\B

A = randn(5)
B = randn(5,1)

x1 = A\B
x2 = inv(A)*B % inv() performs matrix inversion

A =

0.8774 -0.1936 0.5712 0.6825 -1.9796


-1.1566 -0.1576 0.5184 -0.7971 -0.6150
-0.4346 0.9342 0.2793 -1.8054 -0.5038
0.1135 -1.7825 -1.3907 -0.0204 1.3604
0.9226 0.9238 0.4709 -1.0997 -0.3535

B =

-1.6036
0.8091

10
Matlab brief tutorial

1.7550
-0.0805
2.6687

x1 =

0.9623
-0.8440
2.7553
-1.6458
1.5467

x2 =

0.9623
-0.8440
2.7553
-1.6458
1.5467

|'| takes the hermitian of a matrix. |.'| transposes it.

z = a+j*b % j is a constant

z_herm = z'
z_trasp = z.'

z =

-0.8380 + 0.9724i -0.1900 - 1.0063i -0.0787 - 1.3667i -1.7703 + 1.4398


-1.1438 - 1.0553i 0.4207 - 1.1227i -1.3214 + 0.7456i 0.7532 + 0.6397
-2.2245 - 1.0872i 0.7608 - 1.5828i 0.3525 - 0.9520i -0.8529 - 1.0355

z_herm =

-0.8380 - 0.9724i -1.1438 + 1.0553i -2.2245 + 1.0872i


-0.1900 + 1.0063i 0.4207 + 1.1227i 0.7608 + 1.5828i
-0.0787 + 1.3667i -1.3214 - 0.7456i 0.3525 + 0.9520i
-1.7703 - 1.4398i 0.7532 - 0.6397i -0.8529 + 1.0355i

z_trasp =

-0.8380 + 0.9724i -1.1438 - 1.0553i -2.2245 - 1.0872i


-0.1900 - 1.0063i 0.4207 - 1.1227i 0.7608 - 1.5828i
-0.0787 - 1.3667i -1.3214 + 0.7456i 0.3525 - 0.9520i
-1.7703 + 1.4398i 0.7532 + 0.6397i -0.8529 - 1.0355i

Array operators perform elementwise operations

11
Matlab brief tutorial

Elementwise product

ab = a.*b

ab =

-0.8149 0.1912 0.1075 -2.5488


1.2072 -0.4723 -0.9852 0.4818
2.4186 -1.2042 -0.3356 0.8832

Elementwise division

ba = a./b

ba =

-0.8617 0.1888 0.0576 -1.2296


1.0839 -0.3747 -1.7724 1.1773
2.0460 -0.4807 -0.3703 0.8237

Elementwise power

a5 = A.^5

a5 =

0.5201 -0.0003 0.0608 0.1481 -30.4035


-2.0701 -0.0001 0.0374 -0.3219 -0.0880
-0.0155 0.7117 0.0017 -19.1827 -0.0324
0.0000 -17.9931 -5.2024 -0.0000 4.6599
0.6684 0.6726 0.0232 -1.6082 -0.0055

which is different from ^

ampow5 = A^5

ampow5 =

26.0089 -15.7019 -2.6425 20.2736 -18.7352


-24.2961 16.4000 12.3783 -19.8470 -6.2211
-23.5512 29.7664 20.7310 -35.3572 -7.4780
19.0808 -30.2084 -22.5504 22.6103 15.7587
-0.0258 19.1475 11.5044 -19.3778 -1.2395

Same result on real matrices

a_herm = a'

12
Matlab brief tutorial

a_trasp = a.'

a_herm =

-0.8380 -1.1438 -2.2245


-0.1900 0.4207 0.7608
-0.0787 -1.3214 0.3525
-1.7703 0.7532 -0.8529

a_trasp =

-0.8380 -1.1438 -2.2245


-0.1900 0.4207 0.7608
-0.0787 -1.3214 0.3525
-1.7703 0.7532 -0.8529

size of a matrix

size(a)
size(a,1) % Rows
size(a,2) % Columns
size(Aempty)

ans =

3 4

ans =

ans =

ans =

0 0

Matrices can be concatenated like elements of a matrix

Conc = [randn(4) ones(4,2); eye(3) zeros(3)]

Conc =

-0.3198 -0.4092 -0.1084 -0.6874 1.0000 1.0000

13
Matlab brief tutorial

-0.5632 1.2922 0.6298 0.0881 1.0000 1.0000


0.7212 0.7626 1.0398 -0.7203 1.0000 1.0000
-0.2140 3.5214 0.2222 0.3207 1.0000 1.0000
1.0000 0 0 0 0 0
0 1.0000 0 0 0 0
0 0 1.0000 0 0 0

Which size will Conc have?

size(Conc)

ans =

7 6

Array indexing
Read the element of A positioned on 5th row and 8th column

A = randn(5,8)

A =

Columns 1 through 7

2.1277 0.3068 -1.4784 0.6193 1.1220 -0.1772 -0.7893


-2.3367 -0.7322 0.5752 0.4263 0.9210 -2.6973 0.4241
-0.0381 0.4215 -0.9627 0.1025 0.4017 0.3031 0.5714
-0.5468 0.8896 0.6207 -0.9929 0.9076 -1.4990 0.4055
-0.9498 -0.7648 0.0968 -0.8502 -1.3678 0.4723 1.5286

Column 8

0.6117
0.3538
0.7736
1.5026
0.3575

indexes start from 1 (not like C, C++ ...)

address a single element with brackets. Read

a34 = A(3,4)

a34 =

0.1025

14
Matlab brief tutorial

it must be within matrix size, otherwise an error is generated

% a39 = A(3,9)

address a single element with brackets. Assign

A(4,5) = 100

A =

Columns 1 through 7

2.1277 0.3068 -1.4784 0.6193 1.1220 -0.1772 -0.7893


-2.3367 -0.7322 0.5752 0.4263 0.9210 -2.6973 0.4241
-0.0381 0.4215 -0.9627 0.1025 0.4017 0.3031 0.5714
-0.5468 0.8896 0.6207 -0.9929 100.0000 -1.4990 0.4055
-0.9498 -0.7648 0.0968 -0.8502 -1.3678 0.4723 1.5286

Column 8

0.6117
0.3538
0.7736
1.5026
0.3575

it can lie outside matrix size. Matrix will be padded with 0s

A(3,9) = 555

A =

Columns 1 through 7

2.1277 0.3068 -1.4784 0.6193 1.1220 -0.1772 -0.7893


-2.3367 -0.7322 0.5752 0.4263 0.9210 -2.6973 0.4241
-0.0381 0.4215 -0.9627 0.1025 0.4017 0.3031 0.5714
-0.5468 0.8896 0.6207 -0.9929 100.0000 -1.4990 0.4055
-0.9498 -0.7648 0.0968 -0.8502 -1.3678 0.4723 1.5286

Columns 8 through 9

0.6117 0
0.3538 0
0.7736 555.0000
1.5026 0
0.3575 0

Address a row. : means "every"

15
Matlab brief tutorial

A(3,:)

ans =

Columns 1 through 7

-0.0381 0.4215 -0.9627 0.1025 0.4017 0.3031 0.5714

Columns 8 through 9

0.7736 555.0000

Address a column

A(:,4)

ans =

0.6193
0.4263
0.1025
-0.9929
-0.8502

indexes are actually vectors

A(2:4,3:5)

ans =

0.5752 0.4263 0.9210


-0.9627 0.1025 0.4017
0.6207 -0.9929 100.0000

all even rows. Note the use of keyword end wich means "last element of"

A(2:2:end,:)

ans =

Columns 1 through 7

-2.3367 -0.7322 0.5752 0.4263 0.9210 -2.6973 0.4241


-0.5468 0.8896 0.6207 -0.9929 100.0000 -1.4990 0.4055

Columns 8 through 9

0.3538 0

16
Matlab brief tutorial

1.5026 0

take the 3rd, the 6th and the 7th element of 5th row

A(5,[3 6 7])

ans =

0.0968 0.4723 1.5286

vectorize a matrix

A_vec = A(:)
size(A_vec)

A_vec =

2.1277
-2.3367
-0.0381
-0.5468
-0.9498
0.3068
-0.7322
0.4215
0.8896
-0.7648
-1.4784
0.5752
-0.9627
0.6207
0.0968
0.6193
0.4263
0.1025
-0.9929
-0.8502
1.1220
0.9210
0.4017
100.0000
-1.3678
-0.1772
-2.6973
0.3031
-1.4990
0.4723
-0.7893
0.4241
0.5714
0.4055

17
Matlab brief tutorial

1.5286
0.6117
0.3538
0.7736
1.5026
0.3575
0
0
555.0000
0
0

ans =

45 1

vectors are addressed in the same way by a single index

A_vec(5)
A_vec(1:2:end)

ans =

-0.9498

ans =

2.1277
-0.0381
-0.9498
-0.7322
0.8896
-1.4784
-0.9627
0.0968
0.4263
-0.9929
1.1220
0.4017
-1.3678
-2.6973
-1.4990
-0.7893
0.5714
1.5286
0.3538
1.5026
0
555.0000
0

18
Matlab brief tutorial

Conditional indexing

G = randn(5)
G>0
H = zeros(size(G))
H(G>0) = 10
H(G<0) = -5
%
Pos_Index = find(G>0)
Neg_Index = find(G<0)

G(Pos_Index)
G(G>0)
G(Neg_Index)
G(G<0)

G =

-0.2324 0.3793 0.1371 -0.3835 -0.7224


-0.0883 0.3244 -1.2577 2.2697 2.5006
0.2226 0.4482 -1.0924 0.6960 -0.5684
1.9802 0.1283 -1.1220 -0.1058 0.9096
-0.3559 0.4914 0.7555 0.0726 -0.1725

ans =

0 1 1 0 0
0 1 0 1 1
1 1 0 1 0
1 1 0 0 1
0 1 1 1 0

H =

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

H =

0 10 10 0 0
0 10 0 10 10
10 10 0 10 0
10 10 0 0 10
0 10 10 10 0

19
Matlab brief tutorial

H =

-5 10 10 -5 -5
-5 10 -5 10 10
10 10 -5 10 -5
10 10 -5 -5 10
-5 10 10 10 -5

Pos_Index =

3
4
6
7
8
9
10
11
15
17
18
20
22
24

Neg_Index =

1
2
5
12
13
14
16
19
21
23
25

ans =

0.2226
1.9802
0.3793
0.3244
0.4482
0.1283
0.4914
0.1371
0.7555

20
Matlab brief tutorial

2.2697
0.6960
0.0726
2.5006
0.9096

ans =

0.2226
1.9802
0.3793
0.3244
0.4482
0.1283
0.4914
0.1371
0.7555
2.2697
0.6960
0.0726
2.5006
0.9096

ans =

-0.2324
-0.0883
-0.3559
-1.2577
-1.0924
-1.1220
-0.3835
-0.1058
-0.7224
-0.5684
-0.1725

ans =

-0.2324
-0.0883
-0.3559
-1.2577
-1.0924
-1.1220
-0.3835
-0.1058
-0.7224
-0.5684
-0.1725

21
Matlab brief tutorial

Workspace
All variables are stored in the workspace. Workspace can be saved on file

save myWorkspace

You can clear selected variables

clear A A_vec

or emptied

clear

and restored

load myWorkspace

Strings
Strings must be created within |'|s and can be assigned to variables

myString = 'My string'

myString =

My string

strings are arrays of chars

myString(4)

ans =

so as vectors they can be concatenated

myConcat = [myString ' does not have a meaning']

myConcat =

My string does not have a meaning

respecting sizes: wrong

% ['ciao';'come'; 'va?']

correct

22
Matlab brief tutorial

['ciao';'come'; 'va? ']

ans =

ciao
come
va?

It's useful to convert numbers to strings with num2str

f = 71;
c = (f-32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']

tempText =

Temperature is 21.6667C

Functions
MATLAB provides a large number of functions that perform computational tasks. Functions are equivalent
to subroutines or methods in other programming languages.

A = [1 3 5];
B = [10 6 4];

To call a function, enclose its input arguments in parentheses:

max(A)

ans =

If there are multiple input arguments, separate them with commas:

max(A,B)

ans =

10 6 5

Return output from a function by assigning it to a variable:

maxA = max(A);

When there are multiple output arguments, enclose them in square brackets

23
Matlab brief tutorial

[maxA,location] = max(A);

Enclose any character string inputs in single quotes:

disp('hello world'); % disp displays the content of the variable

hello world

To call a function that does not require any inputs and does not return any outputs, type only the function
name:

clc % The clc function clears the Command Window.

Plots
Create a new figure object and the data set. We want to plot sin(x) from 0 to 2*pi in steps of pi/100

figure;
x = 0:pi/50:2*pi;
y_sin = sin(x);
plot(x,y_sin)

We can label the axes

xlabel('x')
ylabel('y')

24
Matlab brief tutorial

And give the plot a title

title('Plot of the Sine Function')

25
Matlab brief tutorial

And add a grid overlay

grid on

26
Matlab brief tutorial

To superimpose different data, we hold the graph and draw the cos in dashed red with diamond marker.
Then we release the plot in the end.

hold on
y_cos = cos(x);
plot(x, y_cos, 'rd--');
hold off

27
Matlab brief tutorial

We can also add a legend

legend('sin','cos');

28
Matlab brief tutorial

And focus on a specific axis range

axis([0 pi/2 0 1]);

29
Matlab brief tutorial

Instead, we may want to generate a 2x1 subplot Generate a 2x1 subplot and place sin plot in slot #1

figure;
subplot(2,1,1);
plot(x,y_sin)
xlabel('x')
ylabel('sin(x)')
title('Plot of the Sine Function')
grid on

30
Matlab brief tutorial

then move to slot #2 and place cos plot

subplot(2,1,2);
plot(x,y_cos)
xlabel('x')
ylabel('cos(x)')
title('Plot of the Cosine Function')
grid on

31
Matlab brief tutorial

Other useful plots: histogram

z = randn(10000,1);
figure;
hist(z,100)

32
Matlab brief tutorial

stem plot

figure;
stem(x, y_sin)

33
Matlab brief tutorial

logaritmic plot

x = 0:0.01:3;
y = exp(-x.^2); % Note the .^

Linear plot

figure;
plot(x,y);
grid on;

34
Matlab brief tutorial

Logaritmic on y axis

figure;
semilogy(x,y);
grid on;

35
Matlab brief tutorial

Logaritmic on both axis

figure;
loglog(x,y)
grid on;

36
Matlab brief tutorial

close all figures with close all;

Scripting
Scripts are trivially sequences of operations. This file itself is a script. Scripts are ASCII files with .m
extension and can be run typing their filename, if they are placed in current directory or in matlab path

myScript

This is a script

37
Matlab brief tutorial

Type a script content

type myScript.m

clc;
disp('This is a script');
% This is a comment

% Generate random data from a uniform distribution


% and calculate the mean. Plot the data and the mean.

n = 50; % 50 data points


r = rand(n,1);
plot(r,'ko')

% Draw a line from (0,m) to (n,m)


m = mean(r);
hold on
plot([0,n],[m,m],'--')
hold off
title('Mean of Random Uniform Data')

scripts can be terminated by Ctrl+C

Moreover, custom functions can be written. They have optional inputs and optional outputs.

numberOfData = 10000;

38
Matlab brief tutorial

a = -5;
b = 9;

[meanData, varianceData] = myFunction(numberOfData, a, b);


disp(['Analytical average is ' num2str((a+b)/2)]);
disp(['Experimental average is ' num2str(meanData)]);
disp(['Analytical variance is ' num2str((b-a).^2./12)]);
disp(['Experimental variance is ' num2str(varianceData)]);

Analytical average is 2
Experimental average is 1.9593
Analytical variance is 16.3333
Experimental variance is 16.5392

You can also provide help to custom functions

help myFunction

type myFunction.m

MYFUNCTION Evaluates average and variance of uniform distribution


numberOfData is the number of samples the evaluation is performed on
minimum is the minimum of uniform distribution
maximum is the minimum of uniform distribution

function [ average, variance ] = myFunction( numberOfData, minimum, maximum


%MYFUNCTION Evaluates average and variance of uniform distribution
% numberOfData is the number of samples the evaluation is performed on
% minimum is the minimum of uniform distribution
% maximum is the minimum of uniform distribution

x = (maximum-minimum)*rand(numberOfData, 1) + minimum;

average = mean(x);
variance = var(x);

end

Loops and conditional statements


Loops are created using for keyword (also while exists). Both are terminated with an end

a = -5;
b = 9;
for numberOfData = 1:100:1000
[meanData, varianceData] = myFunction(numberOfData, a, b)
end

meanData =

39
Matlab brief tutorial

2.6559

varianceData =

meanData =

1.8471

varianceData =

13.5024

meanData =

2.0073

varianceData =

15.5088

meanData =

2.1701

varianceData =

17.0583

meanData =

1.9149

varianceData =

15.7605

meanData =

2.4773

varianceData =

40
Matlab brief tutorial

16.4590

meanData =

1.9687

varianceData =

15.4077

meanData =

1.9147

varianceData =

16.4750

meanData =

2.1541

varianceData =

15.8925

meanData =

1.9696

varianceData =

15.6236

adding some output

for numberOfData = 1:100:1000


disp('=================================================================');
disp(['number of data is ' num2str(numberOfData)]);
[meanData, varianceData] = myFunction(numberOfData, a, b);
disp(['Analytical average is ' num2str((a+b)/2)]);
disp(['Experimental average is ' num2str(meanData)]);
disp(['Analytical variance is ' num2str((b-a).^2./12)]);
disp(['Experimental variance is ' num2str(varianceData)]);

41
Matlab brief tutorial

end

=================================================================
number of data is 1
Analytical average is 2
Experimental average is 7.2682
Analytical variance is 16.3333
Experimental variance is 0
=================================================================
number of data is 101
Analytical average is 2
Experimental average is 1.7266
Analytical variance is 16.3333
Experimental variance is 17.1855
=================================================================
number of data is 201
Analytical average is 2
Experimental average is 1.7864
Analytical variance is 16.3333
Experimental variance is 15.526
=================================================================
number of data is 301
Analytical average is 2
Experimental average is 1.8202
Analytical variance is 16.3333
Experimental variance is 15.945
=================================================================
number of data is 401
Analytical average is 2
Experimental average is 2.0725
Analytical variance is 16.3333
Experimental variance is 16.8322
=================================================================
number of data is 501
Analytical average is 2
Experimental average is 2.1756
Analytical variance is 16.3333
Experimental variance is 17.5256
=================================================================
number of data is 601
Analytical average is 2
Experimental average is 2.0129
Analytical variance is 16.3333
Experimental variance is 17.8098
=================================================================
number of data is 701
Analytical average is 2
Experimental average is 1.8945
Analytical variance is 16.3333
Experimental variance is 16.3965
=================================================================
number of data is 801
Analytical average is 2
Experimental average is 2.0589

42
Matlab brief tutorial

Analytical variance is 16.3333


Experimental variance is 16.2091
=================================================================
number of data is 901
Analytical average is 2
Experimental average is 2.2746
Analytical variance is 16.3333
Experimental variance is 16.4087

and an |if| statement


if(condition)
if true
else
if false
end

% Relation operators are ==, ~=, >, <, >=, <=


% Logical operators are &, |, ~

for numberOfData = 1:100:1000


disp('=================================================================');
disp(['number of data is ' num2str(numberOfData)]);
[meanData, varianceData] = myFunction(numberOfData, a, b);
disp(['Analytical average is ' num2str((a+b)/2)]);
disp(['Experimental average is ' num2str(meanData)]);
if(meanData > (a+b)/2)
disp('Experimental above analytical');
elseif(meanData == (a+b)/2)
disp('Experimental exactly equal to analytical');
else
disp('Experimental below analytical');
end
end

=================================================================
number of data is 1
Analytical average is 2
Experimental average is -4.1981
Experimental below analytical
=================================================================
number of data is 101
Analytical average is 2
Experimental average is 2.1602
Experimental above analytical
=================================================================
number of data is 201
Analytical average is 2
Experimental average is 2.3187
Experimental above analytical
=================================================================
number of data is 301
Analytical average is 2
Experimental average is 2.2856
Experimental above analytical

43
Matlab brief tutorial

=================================================================
number of data is 401
Analytical average is 2
Experimental average is 2.1306
Experimental above analytical
=================================================================
number of data is 501
Analytical average is 2
Experimental average is 1.8083
Experimental below analytical
=================================================================
number of data is 601
Analytical average is 2
Experimental average is 1.952
Experimental below analytical
=================================================================
number of data is 701
Analytical average is 2
Experimental average is 1.9895
Experimental below analytical
=================================================================
number of data is 801
Analytical average is 2
Experimental average is 1.919
Experimental below analytical
=================================================================
number of data is 901
Analytical average is 2
Experimental average is 1.7279
Experimental below analytical

Final example

numberOfData = 1:100:1000;
meanData = zeros(size(numberOfData)); % optional
for ii = 1:length(numberOfData)
[meanData(ii), varianceData] = myFunction(numberOfData(ii), a, b);
end
figure;
plot(numberOfData, meanData,'rx');
hold on;
plot([numberOfData(1) numberOfData(end)], [(a+b)/2 (a+b)/2]);

44
Matlab brief tutorial

Final hint
Matlab works very well with matrix/vector calculations. When possible, use matrix operations rather than
for loops

A is a NxN square invertible matrix X is an unknown NxM matrix B is a given NxM matrix Find the 1xM
vector of column-averages of X such that X is the solution to A*X = B

N = 100;
M = 10000;
A = randn(N);
B = randn(N,M);

Bad Solution:

tic;
for ii = 1:M
b_temp = B(:,ii);
x_temp = inv(A)*b_temp;
averages_bad(ii) = mean(x_temp);
end
toc

Elapsed time is 4.260555 seconds.

Intermediate solution

45
Matlab brief tutorial

tic;
averages_interm = zeros(1,M);
inv_A = inv(A);
for ii = 1:M
b_temp = B(:,ii);
x_temp = inv_A*b_temp;
averages_interm(ii) = mean(x_temp);
end
toc

Elapsed time is 0.365220 seconds.

Best solution

tic;
averages_best = mean(A\B);
toc

% disp([averages_bad.' averages_interm.' averages_best.']);

Elapsed time is 0.020522 seconds.

Published with MATLAB® R2014a

46

Vous aimerez peut-être aussi