Matlab Brief Tutorial: Introductory Concepts
Matlab Brief Tutorial: Introductory Concepts
Matlab Brief Tutorial: Introductory Concepts
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
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 =
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
% b
Let's define it
b = 3
1
Matlab brief tutorial
b =
c = a+b
d = a/b
c =
d =
1.6667
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
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
z =
5.0000 + 3.0000i
y =
8.0000 + 1.6667i
ans =
ans =
1.6667
ans =
5.8310
ans =
0.2054
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 =
% 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.
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
zeri = zeros(2,3)
zeri =
0 0 0
0 0 0
help zeros
ZEROS(..., 'like', Y) is an array of zeros with the same data type, spa
and complexity (real or complex) as the numeric variable Y.
5
Matlab brief tutorial
Example:
x = zeros(2,3,'int8');
Overloaded methods:
distributed/zeros
codistributor2dbc/zeros
codistributor1d/zeros
codistributed/zeros
gpuArray/zeros
unif1 = rand(4,4)
unif1 =
but also
unif2 = rand(4)
unif2 =
help rand
6
Matlab brief tutorial
Examples:
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
Overloaded methods:
RandStream/rand
distributed/rand
codistributor2dbc/rand
codistributor1d/rand
7
Matlab brief tutorial
codistributed/rand
gpuArray/rand
Aempty = []
Aempty =
[]
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
a1to20step2 = 1:2:20
a1to20step2 =
1 3 5 7 9 11 13 15 17 19
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 =
ans =
ans =
b = randn(3,4)
c = a+b
d = a-b
b =
c =
9
Matlab brief tutorial
d =
e = ones(4,2);
% f = a+e
f = b*e
f =
0.0392 0.0392
-0.7928 -0.7928
-4.6575 -4.6575
% 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 =
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
z = a+j*b % j is a constant
z_herm = z'
z_trasp = z.'
z =
z_herm =
z_trasp =
11
Matlab brief tutorial
Elementwise product
ab = a.*b
ab =
Elementwise division
ba = a./b
ba =
Elementwise power
a5 = A.^5
a5 =
ampow5 = A^5
ampow5 =
a_herm = a'
12
Matlab brief tutorial
a_trasp = a.'
a_herm =
a_trasp =
size of a matrix
size(a)
size(a,1) % Rows
size(a,2) % Columns
size(Aempty)
ans =
3 4
ans =
ans =
ans =
0 0
Conc =
13
Matlab brief tutorial
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
Column 8
0.6117
0.3538
0.7736
1.5026
0.3575
a34 = A(3,4)
a34 =
0.1025
14
Matlab brief tutorial
% a39 = A(3,9)
A(4,5) = 100
A =
Columns 1 through 7
Column 8
0.6117
0.3538
0.7736
1.5026
0.3575
A(3,9) = 555
A =
Columns 1 through 7
Columns 8 through 9
0.6117 0
0.3538 0
0.7736 555.0000
1.5026 0
0.3575 0
15
Matlab brief tutorial
A(3,:)
ans =
Columns 1 through 7
Columns 8 through 9
0.7736 555.0000
Address a column
A(:,4)
ans =
0.6193
0.4263
0.1025
-0.9929
-0.8502
A(2:4,3:5)
ans =
all even rows. Note the use of keyword end wich means "last element of"
A(2:2:end,:)
ans =
Columns 1 through 7
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 =
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
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 =
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
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(4)
ans =
myConcat =
% ['ciao';'come'; 'va?']
correct
22
Matlab brief tutorial
ans =
ciao
come
va?
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];
max(A)
ans =
max(A,B)
ans =
10 6 5
maxA = max(A);
When there are multiple output arguments, enclose them in square brackets
23
Matlab brief tutorial
[maxA,location] = max(A);
hello world
To call a function that does not require any inputs and does not return any outputs, type only the function
name:
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)
xlabel('x')
ylabel('y')
24
Matlab brief tutorial
25
Matlab brief tutorial
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
legend('sin','cos');
28
Matlab brief tutorial
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
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
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
figure;
loglog(x,y)
grid on;
36
Matlab brief tutorial
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 myScript.m
clc;
disp('This is a script');
% This is a comment
Moreover, custom functions can be written. They have optional inputs and optional outputs.
numberOfData = 10000;
38
Matlab brief tutorial
a = -5;
b = 9;
Analytical average is 2
Experimental average is 1.9593
Analytical variance is 16.3333
Experimental variance is 16.5392
help myFunction
type myFunction.m
x = (maximum-minimum)*rand(numberOfData, 1) + minimum;
average = mean(x);
variance = var(x);
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
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
=================================================================
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
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
Best solution
tic;
averages_best = mean(A\B);
toc
46