Introdução ao MATLAB
M
ATLAB
Basico
Introduction to M
ATLAB
Online Help
•
The help command
>> help
•
The help window
>> helpwin
•
The lookfor command
>> lookfor
»
help cdCD Change current working directory.
CD directory-spec sets the current directory to the one specified. CD .. moves to the directory above the current one.
CD, by itself, prints out the current directory. WD = CD returns the current directory as a string.
Use the functional form of CD, such as CD('directory-spec'), when the directory specification is stored in a string.
See also PWD.
»
help cdCD Change current working directory.
CD directory-spec sets the current directory to the one specified. CD .. moves to the directory above the current one.
CD, by itself, prints out the current directory. WD = CD returns the current directory as a string.
Use the functional form of CD, such as CD('directory-spec'), when the directory specification is stored in a string.
Introduction to M
ATLAB
Calculations at the Command Line
»
-5/(4.8+5.32)^2 ans = -0.0488»
(3+4i)*(3-4i) ans = 25»
cos(pi/2) ans = 6.1230e-017»
exp(acos(0.3)) ans = 3.5470»
-5/(4.8+5.32)^2 ans = -0.0488»
(3+4i)*(3-4i) ans = 25»
cos(pi/2) ans = 6.1230e-017»
exp(acos(0.3)) ans = 3.5470 » a = 2; » b = 5; » a^b ans = 32 » x = 5/2*pi; » y = sin(x) y = 1 » z = asin(y) z = 1.5708 » a = 2; » b = 5; » a^b ans = 32 » x = 5/2*pi; » y = sin(x) y = 1 » z = asin(y) z = 1.5708 Results assigned to “ans” if name not specified»cmd_line
() parentheses for function inputs Semicolon suppresses screen outputMATLAB as a calculator
Assigning Variables
Numbers stored in double-precision
floating point format
Introduction to M
ATLAB
Working with Files & Variables
•
CD / PWD, LS / DIR - navigating directories
•
WHAT - displays the files within a directory
(grouped by type)
•
! - invoke operating system
•
WHICH - identifies the object referenced by given
name (function / variable)
•
CLEAR - remove function / variable from memory
•
WHOS - lists workspace variables and details
(size, memory usage, data type)
•
SIZE - returns the size of matrix
Introduction to M
ATLAB
»workspace
Command line
variables saved in
MATLAB workspace
Workspace Browser
Introduction to M
ATLAB
»openvar ans
Array Editor
double-click /
Open
For editing 2-D
numeric arrays
Introduction to M
ATLAB
Working with Matrices
MATLAB == MATrix LABoratory
»load durer
»image(X);
»colormap(map)
»load detail
»image(X);
»colormap(map)
Introduction to M
ATLAB
The Matrix in MATLAB
4
10
1
6
2
8
1.2
9
4
25
7.2
5
7
1
11
0
0.5
4
5
56
23
83
13
0
10
1
2
Rows (m) 3
4
5
Columns
(n)
1 2 3 4 5
1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25A =
A (2,4)
A (17)
Rectangular Matrix:
Scalar: 1-by-1 array
Vector: m-by-1 array
1-by-n array
Matrix: m-by-n array
Matrix elements can be EITHER
Introduction to M
ATLAB
Any MATLAB expression can
be entered as a matrix element
Entering Numeric Arrays
» a=[1 2;3 4] a = 1 2 3 4 » b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = -2.8000 0 + 2.6458i 10.5000 » b(2,5) = 23 b = -2.8000 0 + 2.6458i 10.5000 0 0 0 0 0 0 23.0000 » a=[1 2;3 4] a = 1 2 3 4 » b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = -2.8000 0 + 2.6458i 10.5000 » b(2,5) = 23 b = -2.8000 0 + 2.6458i 10.5000 0 0 0 0 0 0 23.0000
Row separator:
semicolon (;)
Column separator:
space / comma (,)
»num_array1
Use square
brackets [ ]
Matrices must
be rectangular.
(Set undefined elements to zero)Introduction to M
ATLAB
Entering Numeric Arrays - cont.
» w=[1 2;3 4] + 5 w = 6 7 8 9 » x = 1:5 x = 1 2 3 4 5 » y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4) z = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185 » w=[1 2;3 4] + 5 w = 6 7 8 9 » x = 1:5 x = 1 2 3 4 5 » y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4) z = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
Scalar expansion
Creating
sequences:
colon operator (:)
Utility functions for
creating matrices.
(Ref: Utility Commands)Introduction to M
ATLAB
Numerical Array Concatenation - [ ]
»num_cat
» a=[1 2;3 4]
a =
1 2 3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24 » a=[1 2;3 4] a = 1 2 3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
Use [ ] to combine
existing arrays as
matrix “elements”
Row separator:
semicolon (;)
Column separator:
space / comma (,)
Use square
brackets [ ]
The resulting
matrix must
be rectangular.
4*a
Introduction to M
ATLAB
Array Subscripting / Indexing
4
10
1
6
2
8
1.2
9
4
25
7.2
5
7
1
11
0
0.5
4
5
56
23
83
13
0
10
1
2
3
4
5
1 2 3 4 5
1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25A =
A(3,1)
A(3)
A(1:5,5)
A(:,5)
A(21:25)
A(4:5,2:3)
A([9 14;10 15])
• Use () parentheses to specify index
• colon operator (:) specifies range / ALL
• [ ] to create matrix of index subscripts
• ‘end’ specifies maximum index value
A(1:end,end)
A(:,end)
Introduction to M
ATLAB
•
Create a 5x5 Pascal matrix ("P_mat")
•
Extract elements to create row vectors
for the first 5 rows of Pascal’s Triangle
(Look for patterns in the element locations in "P_mat")
•
Combine the vectors into a single
matrix with zeros above the diagonal
"P_mat"
Exercise: Creating Matrices
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 . . . Pascal’s Triangle 1 0 0 0 0 1 1 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1 1 0 0 0 0 1 1 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1 1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 70 1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 70 row1 = 1 row2 = 1 1 row3 = 1 2 1 row4 = 1 3 3 1 row5 = 1 4 6 4 1 row1 = 1 row2 = 1 1 row3 = 1 2 1 row4 = 1 3 3 1 row5 = 1 4 6 4 1
Introduction to M
ATLAB
Solution: Creating Matrices (1)
» P_mat = pascal(5) % Create Pascal's Matrix
» row1 = P_mat(1) % Extract Rows
» row2 = P_mat(2:4:6) ... » row5 = P_mat(5:4:21)
» new_mat = row1 % Create New Matrix
» new_mat(2,1:2) = row2 ... » new_mat(5,1:5) = row5
% NOTE: GENERALIZED FORM: % Nmax = length(P_mat);
% rowN = P_mat(N:Nmax-1:(N-1)*Nmax+1) % new_mat(N,1:N) = rowN
» P_mat = pascal(5) % Create Pascal's Matrix
» row1 = P_mat(1) % Extract Rows
» row2 = P_mat(2:4:6) ... » row5 = P_mat(5:4:21)
» new_mat = row1 % Create New Matrix
» new_mat(2,1:2) = row2 ... » new_mat(5,1:5) = row5
% NOTE: GENERALIZED FORM: % Nmax = length(P_mat);
% rowN = P_mat(N:Nmax-1:(N-1)*Nmax+1) % new_mat(N,1:N) = rowN
Introduction to M
ATLAB
Solution: Creating Matrices (2)
» P_mat = pascal(5) % Create Pascal's Matrix % Rearrange Matrix - Pascal Triangle in upper triangle % Flip Matrix Horizontally (LEFT-RIGHT):
% - Could also use FLIPLR():
» temp = P_mat(1:5, 5:-1:1)
% Extract diagonals (rows of Pascal’s Triangle)
» row1 = diag(temp,4)' » row2 = diag(temp,3)' » row3 = diag(temp,2)' » row4 = diag(temp,1)' » row5 = diag(temp)'
% Create New Matrix as before
» P_mat = pascal(5) % Create Pascal's Matrix
% Rearrange Matrix - Pascal Triangle in upper triangle % Flip Matrix Horizontally (LEFT-RIGHT):
% - Could also use FLIPLR():
» temp = P_mat(1:5, 5:-1:1)
% Extract diagonals (rows of Pascal’s Triangle)
» row1 = diag(temp,4)' » row2 = diag(temp,3)' » row3 = diag(temp,2)' » row4 = diag(temp,1)' » row5 = diag(temp)'
% Create New Matrix as before
Introduction to M
ATLAB
Solution: Creating Matrices (3)
» P_mat = pascal(5) % Create Pascal's Matrix % Rearrange Matrix - Pascal Triangle in lower triangle % Flip Matrix Vertically (UP-DOWN):
% - Could also use FLIPUD():
» temp1 = P_mat(5:-1:1, 1:5)
% Extract lower triangular matrix:
» temp2 = tril(temp1)
% Create New Matrix by sorting columns of "temp2":
» new_mat = sort(temp2)
» P_mat = pascal(5) % Create Pascal's Matrix
% Rearrange Matrix - Pascal Triangle in lower triangle % Flip Matrix Vertically (UP-DOWN):
% - Could also use FLIPUD():
» temp1 = P_mat(5:-1:1, 1:5)
% Extract lower triangular matrix:
» temp2 = tril(temp1)
% Create New Matrix by sorting columns of "temp2":
» new_mat = sort(temp2)
Introduction to M
ATLAB
Matrices & Linear Algebra
Matrix Operators
Array operators
() parentheses‘ comp. transpose .’ array transpose ^ power .^ array power * multiplication .* array mult. / division ./ array division \ left division
+ addition - subtraction
»help ops
»help matfun
Common Matrix Functions
inv() matrix inverse det() determinant rank() matrix rank
eig() eigenvectors & values svd() singular value dec. norm() matrix / vector norm
Introduction to M
ATLAB
Matrix Multiplication
•
Inner dimensions must be equal
•
Dimension of resulting matrix = outermost
dimensions of multiplied matrices
•
Resulting elements = dot product of the rows of
the 1st matrix with the columns of the 2nd matrix
» a = [1 2 3 4; 5 6 7 8]; » b = ones(4,3); » c = a*b c = 10 10 10 26 26 26 » a = [1 2 3 4; 5 6 7 8]; » b = ones(4,3); » c = a*b c = 10 10 10 26 26 26 [2x4] [4x3] [2x4]*[4x3] [2x3]
a(2nd row).b(3rd column)
Introduction to M
ATLAB
Solving Simultaneous Equations
using “Left Division”
•
If [A] is square matrix (m = n):
•
For overdetermined system (m>n):
using Least squares regression “curve fit” of dataWarning if rank deficient (dependent columns) - solution not unique
•
For undetermined system (m<n):
using QR factorization with column pivoting Never unique[A]{x} = {b}
{x} = ?
{x} = [A]
-1{b}
» x = inv(A)*b; » x = A\b; » x = inv(A)*b; » x = A\b; Error if singular Warning if nearly singular[A] = mxn {x} = nx1 {b} = mx1 » x = A\b; » x = A\b; » x = A\b; » x = A\b;
Introduction to M
ATLAB
•
Solve this set of simultaneous equations:
Example: Solving Equations
» A = [-1 1 2; 3 -1 1;-1 3 4]; » b = [2;6;4]; » x = inv(A)*b x = 1.0000 -1.0000 2.0000 » x = A\b x = 1.0000 -1.0000 2.0000 » A = [-1 1 2; 3 -1 1;-1 3 4]; » b = [2;6;4]; » x = inv(A)*b x = 1.0000 -1.0000 2.0000 » x = A\b x = 1.0000 -1.0000 2.0000
-x
1
+ x
2
+ 2x
3
= 2
3x
1
- x
2
+ x
3
= 6
-x
1
+ 3x
2
+ 4x
3
= 4
»solve_examp
Introduction to M
ATLAB
Array Multiplication
•
Matrices must have the same dimensions
•
Dimensions of resulting matrix = dimensions of
multiplied matrices
•
Resulting elements = product of corresponding
elements from the original matrices
Same rules apply for other array operations
» a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32 » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32»array_mult
c(2,4) = a(2,4)*b(2,4)Introduction to M
ATLAB
•
In most languages - use loops:
•
In MATLAB - use Array Operations:
Example: Array Operations
»
tic; for I = 1:1000 Density(I) = Mass(I)/(Length(I)*Width(I)*Height(I)); end; toc elapsed_time = 0.0500»
tic; for I = 1:1000 Density(I) = Mass(I)/(Length(I)*Width(I)*Height(I)); end; toc elapsed_time = 0.0500»array_examp
»
tic; Density = Mass./(Length.*Width.*Height); toc elapsed_time =0
»
tic; Density = Mass./(Length.*Width.*Height); toc elapsed_time =0
Use TIC and TOC to
measure elapsed time
Vectorized code is
Introduction to M
ATLAB
Boolean Operations
»
Mass = [-2 10 NaN 30 -11 Inf 31];»
all_pos = all(Mass>=0) all_pos = 0»
each_pos = Mass>=0 each_pos = 0 1 0 1 0 1 1»
pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = 0 1 0 1 0 0 1»
Mass = [-2 10 NaN 30 -11 Inf 31];»
all_pos = all(Mass>=0) all_pos = 0»
each_pos = Mass>=0 each_pos = 0 1 0 1 0 1 1»
pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = 0 1 0 1 0 0 1 Boolean Operators = = equal to > greater than < less than ~ not & and | or isempty() isfinite(), etc. . . . any() all()1 = TRUE
0 = FALSE
»bool_ops
Introduction to M
ATLAB
Exercise: Matrix Operations
•
You are given measured data of current vs. applied DC
voltage for a “black box” circuit
Introduction to M
ATLAB
Solution: Matrix Operations
»mat_ops
(uses: >>mat_ops_setup.m & >>mat_ops.mat)
% Assign loaded data:
» A = voltage; b = current;
% Using left division
» x = A\b
% Using Pseudoinverse
» pseudo_inv_A = inv(A'*A)*A’; » x = pseudo_inv_A*b
% Repeat using linear data
» indices = find(voltage<8);
» A = voltage(indices); b = current(indices); ...
% Assign loaded data:
» A = voltage; b = current;
% Using left division
» x = A\b
% Using Pseudoinverse
» pseudo_inv_A = inv(A'*A)*A’; » x = pseudo_inv_A*b
% Repeat using linear data
» indices = find(voltage<8);
» A = voltage(indices); b = current(indices); ...
Initial Fit
Introduction to M
ATLAB
String Arrays
•
Created using single quote delimiter (')
•
Each character is a separate matrix element
(16 bits of memory per character)
•
Indexing same as for numeric arrays
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
»string_array
1x9 vector
Introduction to M
ATLAB
» str ='Hi there,'; » str1='Everyone!'; » new_str=[str, ' ', str1] new_str = Hi there, Everyone!» str2 = 'Isn''t MATLAB great?'; » new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone! Isn't MATLAB great?
» str ='Hi there,'; » str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =
Hi there, Everyone!
» str2 = 'Isn''t MATLAB great?'; » new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone! Isn't MATLAB great?
1x19 vector
1x9 vectors
String Array Concatenation
»string_cat
Using [ ] operator:
Each row must be same length
Row separator:
semicolon (;)
Column separator:
space / comma (,)
For strings of different length:
• STRVCAT
• STR2MAT
» new_str3 = strvcat(str, str2)new_str3 =
Hi there, Isn't MATLAB great?
» new_str3 = strvcat(str, str2)
new_str3 =
Hi there, Isn't MATLAB great?
2x19 matrix
2x19 matrix
(zero padded)
1x19 vectors
Introduction to M
ATLAB
Working with String Arrays
String Comparisons
•
STRCMP - compare whole strings
•
STRNCMP - compare first ‘N’ characters
•
FINDSTR - finds substring within a larger string
Converting between numeric & string arrays:
•
NUM2STR - convert from numeric to string array
Introduction to M
ATLAB
Exercise: String Arrays
•
Create a 5x5 magic matrix ("M")
•
Use "M" to create a string array which will
display as follows:
» disp(string_array) 5x5 Magic Matrix: 'A' 'B' 'C' 'D' 'E' 1 17 24 1 8 15 2 23 5 7 14 16 3 4 6 13 20 22 4 10 12 19 21 3 5 11 18 25 2 9 » disp(string_array) 5x5 Magic Matrix: 'A' 'B' 'C' 'D' 'E' 1 17 24 1 8 15 2 23 5 7 14 16 3 4 6 13 20 22 4 10 12 19 21 3 5 11 18 25 2 9Tab character
New line character
HINT:
Create rows
separately &
concatenate
Introduction to M
ATLAB
Solution: String Arrays
» M = magic(5)
» M_string = num2str(M)
» heading = ['5x5 Magic Matrix:', char(10)]
» row0 = [char(9), '''A'' ''B'' ''C'' ''D'' ''E'''] » row1 = ['1', char(9), M_string(1,:)]
» row2 = ['2', char(9), M_string(2,:)] » row3 = ['3', char(9), M_string(3,:)] » row4 = ['4', char(9), M_string(4,:)] » row5 = ['5', char(9), M_string(5,:)]
» string_array = strvcat(heading,row0,row1,row2,row3,row4,row5) » M = magic(5)
» M_string = num2str(M)
» heading = ['5x5 Magic Matrix:', char(10)]
» row0 = [char(9), '''A'' ''B'' ''C'' ''D'' ''E'''] » row1 = ['1', char(9), M_string(1,:)]
» row2 = ['2', char(9), M_string(2,:)] » row3 = ['3', char(9), M_string(3,:)] » row4 = ['4', char(9), M_string(4,:)] » row5 = ['5', char(9), M_string(5,:)]
» string_array = strvcat(heading,row0,row1,row2,row3,row4,row5)