Escolar Documentos
Profissional Documentos
Cultura Documentos
Dagmar Roth
(Karlsruhe Institute of Technology)
This project has been funded with support from the European Commission. This publication
[communication] reflects the views only of the author, and the Commission cannot be held
responsible for any use which may be made of the information contained therein.
Grant Agreement Reference Number:
D-2012-ERA/MOBIP-3-29749-1-6
Tutorial:
An introduction into
MATLAB
MATLAB Overview
http://www.mathworks.com/products/matlab/
MATLAB is a high-level language and interactive environment
for numerical computation, visualization, and programming. Using
MATLAB, you can analyze data, develop algorithms, and create models
and applications. The language, tools, and built-in math functions enable
you to explore multiple approaches and reach a solution faster than with
spreadsheets or traditional programming languages, such as C/C++ or Java.
mathematical functions for linear algebra, statistics, Fourier analysis,
numerical integration, differentiation, ordinary differential equations,
and more
fast execution of vector and matrix calculations
no low-level administrative task such as declaring variables,
specifying data types and allocating memory necessary
(unlike in C(C++) or Fortran)
built-in 2-D and 3-D plotting functions
Many additional and useful toolboxes: symbolic math, parallel
programming, partial differentail equations, optimization, interval
analysis (INTLAB), ...
y = A*x;
Current
Folder
File details
Workspace:
Shows assigned
variables
Command History:
Lists all previously
called commands
Enter Key
Variables
The first character of a name of a variable should be an
alphabetic character and the variable-name should be different
from the name of MATLAB functions (or predefined variables)
Names of variables are case sensitive, i.e. a capital letter is
distinguished from a small letter
Types of a variables do not need to be specified: In assignment,
MATLAB does not distinguish between integers and real numbers
with decimal point
All initialized variables are listed in Workspace-window: Variables
can easily be saved for later sessions or imported from saved data
Special variables
In order to express some special numerical values or
special matrices, some names are fixed as follows:
Name Meaning
pi
Inf, inf
infinity,
i, j, 1i
imaginary unit 1
eps
machine epsilon
( minimal satisfying 1+>1 )
eye(n) unit matrix of dimension n
ones(n,m)
matrix (n rows, m columns) whose all elements are 1
zeros(n,m)
matrix (n rows, m columns) whose all elements are 0
NaN, nan Not a Number
realmin the smallest positive floating point number
which is expressible in a computer
realmax the greatest positive floating point number
which is expressible in a computer
8
>> pi
ans =
3.141592653589793
>> pi=3
pi =
3
>> 10*pi
ans =
30
>> clear pi
>> 10*pi
ans =
31.415926535897931
1 Kings 7,23
And he made a molten sea,
ten cubits from the one brim
to the other: it was round all
about, and his height was
five cubits: and a line of thirty
cubits did compass it round
about.
Perimeter=30
Diameter=10
=> pi=3
9
complex variables
>> z1=1+2*i
z1 =
1 + 2i
>> z2=3+4*j
z2 =
3 + 4i
>> z1+z2
ans =
4 + 6i
Once a value is substituted for i , then
you cannot use i for imaginary unit
until you use clear command in
order to restore it.
how to use
format
12
13
lookfor command
You can search for a keyword in predefined matlab functions
and commands. For example, if you want to find functions
and commands involving max then you may input lookfor max
in the command line.
>> lookfor max
randomc
Complex random numbers in M+i*M with M=[min,max], default [-1,+1]
random
Random numbers in [min,max], default [-1,+1]
Longprecision
Sets/gets maximum precision for long number arithmetic
maxNumCompThreads controls the maximum number of computational threads
Namelengthmax Maximum length of MATLAB function or variable name.
bitmax
Maximum double precision floating point integer.
intmax
Largest positive integer value.
realmax
Largest positive floating point number.
max
Largest component.
runtrackmm
demonstrates using FMINIMAX with Simulink.
dfildemo
minimax Optimization
pdenanmx
NaN protected maximum.
hp2dmax
[alpha,wm,theta,L,P,ejtheta] = hp2dmax(w1,w2,w)
d2dmax
[b,tm,psi,L,P,ejpsi] = d2dmax(t1,t2,theta)
dhinfric
[gopt,K,X1,X2,Y1,Y2] = dhinfric(P,r,gmin,gmax,tol,options)
14
,
x( ,
,
Delete
Ctrl-D
Ctrl-A
Ctrl-E
Ctrl-U
Ctrl-K
15
Arrays
vector one dimensional array
matrix two dimensional array
An index of an array must be a positive integer starting from 1.
>> x=[1 2 3]
x=
1 2 3
>> x'
ans =
1
2
3
>> y=[1;2;3]
y=
1
2
3
>> x=[1:2:7]
x=
1 3 5
>> x=[1:4]
x=
1 2 3
From 1 to 7 incrementing by 2
7
If the increment is 1 then it
can be omitted.
Specify the initial value, last value and the number of element
using the function linspace
>> y=linspace(1,3,5)
y=
1
1.5
2.5
Generate 5 elements
from 1 to 3 with equal
space.
17
>> A=[1 2 3; 4 5 6]
A=
1 2 3
4 5 6
>> A'
ans =
1 4
2 5
3 6
>> a=A(:)
a=
1
4
2
5
3
6
18
>> x=[1 2 3]
x=
1 2 3
>> x(2)
ans =
2
>> A=[1 2 3;4 5 6]
A=
1 2 3
4 5 6
>> A(2,2)
ans =
5
>> A(5,5)
??? Index exceeds matrix dimensions
An error code is
displayed if you
called a
non-existing element.
19
Access to subarrays
( xi )kil
A(k:l,n:m): submatrix ( Aij ) kil
x(k:l): subvector
n j m
>> A=[1,2,3;4,5,6]
A=
1 2 3
4 5 6
>> A(:,1)
ans =
1
4
>> A(1,:)
ans =
1 2 3
expression in MATLAB
a+b
a+b
a -b
a-b
ab
a*b
a/b
a/b
ab
a^b
21
true: 1 false: 0
comparison operation
formula
expression in MATLAB
ab
a<b
ab
a <= b
ab
a>b
ab
a >= b
a=b
a == b
ab
a ~= b
and
&
or
|
22
Example:
23
element-wise operations
For example, for two matrices
A=
1 2
3 4
B=
1 2
2 1
>> A*B
gives
AB=
5 4
11 10
aij bij
(element-wise operation)
>> A .* B
ans =
1 4
6 4
24
a= a1 ,, a n , b=b 1 ,, b n
formula
expression in MATLAB
a1b1 ,, an b n
a1 b1 , , an bn
a .* b
a1 /b 1 ,, an /bn
a ./ b
a1b ,,a bn
a .^ b
a+b
25
Mathematical functions
Various mathematical functions are available in MATLAB.
There are also many mathematical functions in each toolbox.
Use the help command to understand their handling.
Basic mathematical functions
abs
sqrt
log
exp
real
imag
angle
conj
absolute value
square root
natural logarithm
exponential function
real part of a complex variable
imaginary part of a complex variable
argument of a complex variable
conjugate of a complex variable
26
sum of elements
mean value
covariance
correlation coefficient
sort in ascending or descending order
product of elements
cumulative sum
cumulative product
trigonometric functions
sin
cos
tan
asin
acos
atan
sinh
cosh
sin(x)
cos(x)
tan(x)
1
sin 1 x
cos x
1
tan x
sinh(x)
cosh(x)
matrix functions
inv
det
lu
chol
norm
cond
eig
etc
inverse matrix
determinant
LU decomposition
Cholesky decomposition
(various) norms
condition number
eigenvalues
27
Branch, Loop
if statement
if expression1
statement1
elseif expression2
statement2
else
statement3
end
or
if expression1, statement1
elseif expression2, statement2
else statement3
end
28
Example
>> x=-1;
>> if x>0, y=1;
elseif x==0, y=0;
else y=-1;
end
>> y
y=
-1
If x does not have any value then the following error message
appears:
??? Undefined function or variable 'x'.
29
Loop
Several program statements can be repeatedly
executed in a loop. The variable controlling the
repetition is called loop variable.
for
for loop variable = range of the loop variable
statement
end
>> s=0;
>> for i=1:10
s=s+i;
end;
>> disp(s)
55
>> s=0;
>> for i=10:-1:1
s=s+i;
end;
>> disp(s)
55
31
Converse version
32
>> s=0;
>> for k=[1 -1 2 -2 3 -3 4 -4 5 -5]
if k<0, continue;
end
s=s+k;
if s>5, break;
end
disp(s);
end
1
3
If k is negative then go to
next iteration.
If s is greater than 5,
quit the loop.
33
while
while condition
statement
end
>> a=10;
>> while a>=1
a=a/2;
disp(a)
end
5
2.50000000000000
1.25000000000000
0.62500000000000
34
Set Path
Add Folder
35
Exercise:
Write a script fibo.m, that computes all Fibonacci numbers
smaller than 1000 and stores them in an array. Display the
array.
Solution
% An M-file to calculate Fibonacci numbers
f=[1 1]; i=1;
while f(i)+f(i+1)<1000
f(i+2)=f(i)+f(i+1);
i=i+1;
end
disp(f)
plot(f)
>> fibo
Columns 1 through 11
1 1 2 3 5 8 13
Columns 12 through 16
144 233 377 610 987
Size of array is
increased automatically
fibo.m
1000
900
800
21
34
55
89
700
600
500
400
300
200
100
0
10
12
14
37
16
Definition of function
In the beginning of M-file, declare the function with in- and
output parameters as follows:
function [list of output] = function-name(list of input)
Example of function
cal.m
38
Exercise:
Modify fibo.m into a function, that computes all Fibonacci numbers
smaller than some input value M, stores them in an array f and
returns f
Solution
>> f=fibo(1000)
f=
Columns 1 through 11
1 1 2 3 5 8 13
Columns 12 through 16
144 233 377 610 987
21
34
55
fibo.m
89
40
Global variables
The common variables between script and function can be
declared as global variables.
Example
global a b c
a=1; b=2; c=3;
x=1;
y=func(x);
disp(y)
cal2.m
function y=func(x)
global a b c
y=a*x^2 + b*x +c;
func.m
>> cal2
6
41
>> tic;
A=rand(1000,1000);
toc;
elapsed_time = 0.078000
>> tic;
A=rand(1000,1000);
time=toc;
disp(time);
0.07800000000000
Vectorization, High-speed
Vectorization
Some tricks can speed up computations!
Example:
>> clear;
tic;
for j=1:1000
for k=1:1000
A(j,k) = sin(j)+cos(k);
end
end
toc;
Elapsed time is 1.003845 seconds.
Try to optimize
computation time.
Copy code into an m-file:
MATLAB's code analyzer
will give you hints!
43
Step 1
>> clear;
tic;
A=zeros(1000,1000);
for j=1:1000
for k=1:1000
A(j,k) = sin(j)+cos(k);
end
end
toc;
Elapsed time is 0.112592 seconds.
Step 2 (vectorization)
>> clear;
tic;
A=zeros(1000,1000);
j=[1:1000];
sinj = sin(j);
for k=1:1000
A(j,k) = sinj+cos(k);
end
toc;
Elapsed time is 0.010881 seconds.
45
Graphics in 2 dimensions
ezplot displays the graph of function
ezplot(f(x))
Plot f(x) in 2 x2
ezplot(f(x), [a,b])
Plot f(x) in
ezplot(f(x,y))
y 2
Plot f(x,y)=0 in 2 x , y2
ezplot(f(x,y), [a,b])
Plot f(x,y)=0 in
ezplot(f(x,y), [a,b,c,d])
axb
Plot f(x,y)=0 in
ax , yb
axb , c yd
ezplot(x(t)', 'y(t))
0t 2
atb
46
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
-0.2
-0.2
-0.4
-0.4
-0.6
-0.6
-0.8
-0.8
-1
-1
47
Figure 1
Figure 2
48
The graphs of
0
-0.2
-0.4
-0.6
-0.8
-1
49
0
b
g
r
c
m
y
w
k
blue
green
red
cyan
magenta
yellow
white
black
.
o
x
+
*
s
d
v
^
<
>
p
h
dot
circle shape
x shape
plus shape
star shape
square
diamond shape
triangle
inverted triangle
triangle (left direction)
triangle (right direction)
pentagon
hexagon
- solid line
: dotted line
-. chained line
-- broken line
(none) no line
50
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
7
51
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
52
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
-0.2
-0.2
-0.4
-0.4
-0.6
-0.6
-0.8
-1
-0.8
0
-1
53
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
54
Graphics in 3 dimensions
>> t=linspace(0,10,40);
>> [x,y]=meshgrid(t,t);
>> z=sin(x)+cos(y/2);
>> mesh(x,y,z);
1.5
1
0.5
0
-0.5
-1
-1.5
-2
10
8
10
6
8
6
2
0
2
0
55
Alternatively you can use the buttons Save and Import data
on top of workspace window
56
e.g.
>> whos
Name
Size
A
B
fid
i
j
z
100x100
200x200
1x1
1x1
1x1
1x1
Bytes Class
80000 double array
320000 double array
8 double array
8 double array
8 double array
16 double array (complex)
100x100
200x200
1x1
1x1
1x1
1x1
Bytes Class
80000 double array
320000 double array
8 double array
8 double array
8 double array
16 double array (complex)
57