matlab tutorial - doe.carleton.ca
TRANSCRIPT
MATLAB Tutorial
Ehsan Ghias–Begloo Department of Electronics Carleton University [email protected] http://www.doe.carleton.ca/~egbegloo/
Updated September 2013
Intro to Matlab >> % ----------- %{
This is wrap comment; same as /* … */ in C++ or Java
%} %% creates a subsection
MATLAB codes can be saved in “.m” files as scripts & run
accordingly
© 2013 Ehsan Ghias-Begloo 1
Matlab Command Lines start with “>>”
“%” defines comment
Declaring Variables >> a = 1; >> a = 1; b = 2
b = 2
>> global kilo, meg, gig;
© 2013 Ehsan Ghias-Begloo 2
% “;” prevents Matlab from publishing the result of the line
%{ Multiple statements can be in a single line, separated by “,” or “;” }%
% Global variable accessible within all files
Numeric Formats 1.23456789e6 = 1,234,567.89 Output number format:
>> format **** short: 0.5000 short e: 5.0000e–001 long: 0.500000000000000 rational: 1/2 hex: 3fe0000000000000 …
© 2013 Ehsan Ghias-Begloo 3
“%” Short fixed point
“%” Long fixed point
Real vs. Imaginary >> a = 1i + 2
a = 2.0000 + 1.0000i
>> a = 1*i + 2 a = 2.0000 + 1.0000i
>> b = i + 2 b = 2.0000 + 1.0000i
>> i = 1; c = i + 2 c = 3
© 2013 Ehsan Ghias-Begloo 4
Result with variable name
Both “i” & “j” can either represent an imaginary unit or a variable!
% “a” is an imaginary number
%} “b” is an imaginary number since “i” hasn't been defined as a variable; hence it's an imaginary unit }%
%{ “c” is a real number, since “i” has already been defined as a variable, NOT an imaginary unit }%
Defining Vectors 1. >> a = [3 1 7 -21 5 6] or a = [3, 1, 7, -21, 5, 6]
a = 3 1 7 -21 5 6
2. >> b = 1:3:28 b = 1 4 7 10 13 16 19 22 25 28
3. >> c = linspace(1,28,10) c = 1 4 7 10 13 16 19 22 25 28
4. >> l = logspace(4,8,8) l = 1.0e+008 * 0.0001 0.0004 0.0014 0.0052 0.0193 0.0720 0.2683 1.0000
© 2013 Ehsan Ghias-Begloo 5
Same vectors; i.e. b = c
They all create row vectors
Same as c, but in log scale
Vector Elements >> b(5)
ans = 13
>> c(4:7) 10 13 16 19
>> a'
3 1 7 -21 5 6
>> min(a), max(a) -21 7
© 2013 Ehsan Ghias-Begloo 6
“ans” will appear when name is not specified
% Accessing the 5th element of the vector
% Accessing the 4th to 7th elements of the vector
% Transpose the row vector to a column vector
% Minimum and maximum values in the vector
Vectors have their index or subscript begin at 1
Vector Operations >> b + c
2 8 14 20 26 32 38 44 50 56
>> a + b ??? Error using ==> plus Matrix dimensions must agree
>> -3 * b -3 -12 -21 -30 -39 -48 -57 -66 -75 -84
>> c / 2 0.5000 2.0000 3.5000 5.0000 6.5000 8.0000 9.5000 11.0000 12.5000 14.0000
>> c ^ 2 Error using ^ Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead.
>> c .^ 2 1 16 49 100 169 256 361 484 625 784
© 2013 Ehsan Ghias-Begloo 7
One of the most common errors in Matlab
Errors in Matlab are shown this way
% Addition
% Multiplication by a constant
% Division by a constant
% Power to a constant
Proper way
Defining Matrices 1. >> A = [1 2 3; 3 4 5; 6 7 8]
1 2 3 3 4 5 6 7 8
2. >> B = [[4 7 1]' [9 3 6]' [2 5 8]'] 4 9 2 7 3 5 1 6 8
3. >> D = []
4. >> D = [1, D, 2, 3] 1 2 3
5. >> D = [D, a] 1 2 3 3 1 7 -21 5 6
© 2013 Ehsan Ghias-Begloo 8
% “;” adds a row
% Creates an empty matrix; i.e. 0x0
% Matrix concatenation
Defining Matrices 5. >> ones(3)
1 1 1 1 1 1 1 1 1
6. >> zeros(2,5) 0 0 0 0 0 0 0 0 0 0
7. >> rand(3,4) 0.6551 0.4984 0.5853 0.2551 0.1626 0.9597 0.2238 0.5060 0.1190 0.3404 0.7513 0.6991
8. >> A' 1 3 6 2 4 7 3 5 8
© 2013 Ehsan Ghias-Begloo 9
“ones”, “zeros”, and “rand” can generate square or non-square matrices
% Creates a 3x3 square matrix composed of 1s
% Creates a 2x5 matrix composed of 0s
% Matrix transpose
% Creates a 3x2 matrix composed random nubmbers
Matrix Functions >> inv(A)
1.0e+015 * -2.7022 4.5036 -1.8014 5.4043 -9.0072 3.6029 -2.7022 4.5036 -1.8014
>> inv(a) ??? Error using ==> inv Matrix must be square.
>> size(a), size(A) 1 6
3 3
>> length(A) 3
© 2013 Ehsan Ghias-Begloo 10
% Generates the inverse matrix
%{ “inv” is only applicable to square matrices; i.e. cannot use “inv” for vectors }%
% Give size of vectors & matrices
% “size” generates a 1x2 vector defining rows x cols
% Same as max(size(A))
Matrix Extras >> A(2,:)
3 4 5
>> A(:,2) 2 4 7
>> A(2,3) 5
>> A(3,2) 7
>> A(2,2:3) 4 5
© 2013 Ehsan Ghias-Begloo 11
% Returns A’s entire 2nd row
% Returns A’s entire 2nd column
% Element selection – row 3, col 2
% Element selection – 2nd row, cols 2 to 3
% Element selection – row 2, col 3
Matrix Extras >> whos
Name Size Bytes Class Attributes A 3x3 72 double B 3x3 72 double a 1x6 48 double b 1x10 80 double c 1x10 80 double
>> sum(A(2,:))
12
© 2013 Ehsan Ghias-Begloo 12
% Generates a list of variables in the workspace
% Sum of elements in 2nd row
Matrix Operations >> cos(A)
0.5403 -0.4161 -0.9900 -0.9900 -0.6536 0.2837 0.9602 0.7539 -0.1455
>> log10(B) 0.6021 0.9542 0.3010 0.8451 0.4771 0.6990 0 0.7782 0.9031
© 2013 Ehsan Ghias-Begloo 13
An entire matrix can be passed to a function or operation at once; hence, no element by element process is required.
Matrix Operations >> A + B
5 11 5 10 7 10 7 13 16
>> A * B 21 33 36 45 69 66 81 123 111
>> A * a ??? Error using ==> mtimes Inner matrix dimensions must agree.
>> b * c ??? Error using ==> mtimes Inner matrix dimensions must agree.
© 2013 Ehsan Ghias-Begloo 14
% Element by element addition
% Matrix multiplication: A x B
Matrix sizes should match: [m x n] x [n o] = [m x o]
One of the most common errors in Matlab
Matrix Multiplication >> c' * b
1 4 7 10 13 16 19 22 25 28 4 16 28 40 52 64 76 88 100 112 …
>> b * c' 2845
>> M1 = A * B 21 33 36 45 69 66 81 123 111
>> B * A 43 58 73 46 61 76 67 82 97
© 2013 Ehsan Ghias-Begloo 15
% 1x10 x 10x1 => 1x1
% 10x1 x 1x10 => 10x10
AxB ≠ BxA
% M1(m,n) = A(m,:) x B(:,n)
A .* B ≠ A * B
Matrix Multiplication >> M2 = A .* B
4 18 6 21 12 25 6 42 64
>> M3 = cross(A, B) -39 3 0 23 51 -8 -5 -30 5
>> M4 = dot(A,B) 31 72 95
© 2013 Ehsan Ghias-Begloo 16
% Cross product
% Dot product: M4(m) = A(m,:) x B(m,:)
%{ Element by element multiplication: M2(m,n) = A(m,n) x B(m,n) }%
A .* B = B .* A
Matrix Division b / c
1.0000
b ./ c 1 16 49 100 169 256 361 484 625 784
A ./ B 0.2500 0.2222 1.5000 0.4286 1.3333 1.0000 6.0000 1.1667 1.0000
© 2013 Ehsan Ghias-Begloo 17
% Matrix element division – creates a single number
% Element by element division – creates a vector
Matrix Division d = [1 2 3]' A \ d
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 3.469447e-018. 1.0e+015 * 0.9007 -1.8014 0.9007
B \ d 0.0222 0.0222 0.3556
© 2013 Ehsan Ghias-Begloo 18
% Matrix division: Am = b → m = A\v
Mesh >> u = [1 2 3]; v = [4 5 6]; >> u .* v
4 10 18
>> [x, y] = meshgrid(u, v) 1 2 3 1 2 3 1 2 3
4 4 4 5 5 5 6 6 6
>> x .* y 4 8 12 5 10 15 6 12 18
© 2013 Ehsan Ghias-Begloo 19
%{ 1-to-1 relationship for each element of u to only one element of v & vice versa }%
%{ 1-to-1 relationship for each element of u to 3 elements of v & vice versa }%
“meshgrid” replicates the 1x3 grid vectors u & v to produce a full grid. 3x3 x & y contain copies of u & v in each column.
u .* v is the first row of the meshgrid
Mesh
Without meshgrid With meshgrid
© 2013 Ehsan Ghias-Begloo 20
-1-0.8
-0.6-0.4
-0.20
0.20.4
0.60.8
1
-1-0.8
-0.6-0.4
-0.20
0.20.4
0.60.8
10
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
xy
z
-1-0.5
0
0.51
-1
-0.5
0
0.5
10
0.5
1
1.5
2
z = x2 + y2
Finding Roots Nearest zero
>> fzero(@cos, 2) 1.5708
>> fzero(@(x) sin(2*x),2) 1.5708
Polynomial roots >> roots([1,0,2,1])
0.2267 + 1.4677i 0.2267 - 1.4677i -0.4534 + 0.0000i
© 2013 Ehsan Ghias-Begloo 21
% pi/2 % nearest zero of cosine function to 2
% roots of x3+2x+1=0
IF Statements %% Dr. Sheldon Cooper's breakfast schedule … % Any code If day == 'Mon' if brkfast == 'Oatmeal'; brkfastFate= ' Consumed'; end elseif day == 'Sat' if brkfast == 'Cereal with Dr. Who'; brkfastFate= ' Consumed'; end … else brkfastFate = 'Dumped in the garbage'; end
© 2013 Ehsan Ghias-Begloo 22
IF b
lock
s
% 1st IF statement % Inner IF statement
% Else IF
% Equivalent to default statement
For each IF statement, an “end” statement is required at the end of the block
Switch Cases %% Nelson Muntz's response depending on his mood … % Any code
mood = ['hungry', 'angry', 'Martin Prince', …]; switch mood case 'hungry' response = 'Rob lunch'; case 'angry' response = 'Punch'; case 'Martin Prince' response = 'Give wedgie'; …. otherwise response = 'ha ha'; end
© 2013 Ehsan Ghias-Begloo 23
% Case 1
% Case 2
% Case 3
% Default case
% The only “end” statement required, at the end of the block
Sw
itch
blo
ck
Loops 1. For Loop
u = 1:3; C = zeros(3,3); D = []; for i = u'; for j = 1:3; C(i,j) = A(i,j); D = [D, A(i,j)];
end end
1 2 3 3 4 5 6 7 8
2. While Loop % Settlers of Catan game flowchart; whoever reaches 10 wins the game scores = zeros(1,4); while max(scores) < 10 scores = playNextRound(scores); end
© 2013 Ehsan Ghias-Begloo 24
% “D” is an empty matrix; i.e. 0x0
% “i” is assigned a vector
% Cij = Aij
% Concatenating D with Aij
% D
% Game is played until a player's score reaches 10
% Play next round & update “scores”
For
blo
cks
Wh
ile b
lock
% C = A
Subroutines 1. M-File
Function definition function [arrivalYr, realAge] = FuturamaAgeCalctr(f, departureYr, age) travelTime = 1000; arrivalYr = f(departureYr) + travelTime; realAge = age + travelTime;
© 2013 Ehsan Ghias-Begloo 25
% 1st output
% 2nd output
• Needs to be saved on a separate “.m” file. • Outputs are passed in the form of an array. • Does NOT require “end” statement.
Function Name Inputs Outputs
Subroutines Calling the function
PJFry = [1999, 25]; [PJFry(3), PJFry(4)] = FuturamaAgeCalctr(@abs, PJFry (1), PJFry (2)); % Some string to show the results in a sentence str = sprintf('Phillip J. Fry was frozen in year %d, when he was %d. … He was defrosted in year %d, %d years after his birth.', PJFry(1), … PJFry(2), PJFry(3), PJFry(4)); disp(str)
Phillip J. Fry was frozen in year 1999, when he was 25. He was defrosted in year 2999, 1025 years after his birth.
© 2013 Ehsan Ghias-Begloo 26
% Fry's departure year and age
% Results are in the form of an array
% Displaying the string
• File path has to be set to the function location. • Function outputs are in the form of an array.
Subroutines 2. feval [PJF(1) PJF(2)] = feval('FuturamaAgeCalctr', @abs, 1999, 25)
2999 1025
© 2013 Ehsan Ghias-Begloo 27
Another way of Calling an external function
Function Name Inputs
Subroutines 3. inline % Function definition
f = inline('1000 + (x - y)', 'x', 'y'); % Calling the function
f(1999, 1974) 1025
4. @ % Function definition
f = @(x, y) (1000 + (x - y)); % Calling the function
f(1999, 1974) 1025
© 2013 Ehsan Ghias-Begloo 28
Internal function, only accessible within the “.m” file
% Fry's real age in arrival
% Fry's departure and birth year
Similar to inline
2D Plots >> x = -pi:pi/1000:pi; y = sin(x); >> plot(x, y,'r--')
Plot Options
grid on / off title ('Title') xlabel ('X-axis label') ylabel ('Y-axis label') axis ([Xmin Xmax Ymin Ymax]) legend ('A1', 'A2', …, 'Location', 'East')
© 2013 Ehsan Ghias-Begloo 29
-4 -3 -2 -1 0 1 2 3 4-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
-3 -2 -1 0 1 2 3
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
y = Sin(x) vs. x
xy
= si
n(x)
Sin(x)
Histogram A histogram shows the distribution of data values >> mark = 0:12; >> marks = 12*rand(1,100); >> hist(marks, mark)
© 2013 Ehsan Ghias-Begloo 30
0 1 2 3 4 5 6 7 8 9 10 11 120
2
4
6
8
10
12
Mark (F, D-, D, D+, ..., A+)
# of
Stu
dent
s
Distribution of Marks for 100 Students
Other 2D Plots semilogx semilogy loglog scatter stem contour
© 2013 Ehsan Ghias-Begloo 31
Same as 'plot', with a log scale X-axis
Same as 'plot', with a log scale Y-axis
Same as 'plot', with both axis in log scale
Discrete equivalent of 'plot'
Plot options can be used in any plot types!
Same as 'scatter', with stems connected to x-axis
Contour equivalent of 'plot'
Multiple Plots Shared Y-axis
o >> plot(x, sin(x), 'g--', x, cos(x), 'b:')
o >> plot(x, sin(x), 'g--‘) >> hold on >> plot(x, cos(x), 'b:') >> hold on
Double Y-axis >> plotyy(x, sin(x), x, cos(x), 'function')
© 2013 Ehsan Ghias-Begloo 32
-4 -3 -2 -1 0 1 2 3 4-1
-0.5
0
0.5
1
-4 -3 -2 -1 0 1 2 3 4-1
-0.5
0
0.5
1
-4 -3 -2 -1 0 1 2 3 4-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
plot, semilogx, semilogy, loglog, stem, ..
Alternative methods
Subplots Creates several [sub]plots on the same window
>> subplot(1,2,1) >> plot(A, d, 'ms--') >> subplot(1,2,2) >> plot(B, d, 'b^:')
© 2013 Ehsan Ghias-Begloo 33
% 1st plot of a 1x2 window
% 2nd plot of a 1x2 window
-3 -2 -1 0 1 2 3
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Sin(x) vs. x
x
sin(
x)
-3 -2 -1 0 1 2 3
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Cos(x) vs. x
x
Cos
(x)
3D Plots >> t = -10*pi : pi/100 : 10*pi; >> x = t.*cos(t); y = t.*sin(t);
>> plot3(x, y, t);
© 2013 Ehsan Ghias-Begloo 34
-40-30
-20-10
010
2030
40
-30
-20
-10
0
10
20
30-40
-30
-20
-10
0
10
20
30
40
t
(t, t*cos(t), t*sin(t))
t * cos(t)
t * s
in(t)
Other 3D Plots mesh contour3 surf scatter3
© 2013 Ehsan Ghias-Begloo 35
-1
-0.5
0
0.5
1
-1-0.8
-0.6-0.4
-0.20
0.20.4
0.60.8
1
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
xy
z
z = y2 – x2
Need meshgrid inputs
Mathematical Functions abs(x) Absolute value
sqrt(x) Square root
exp(x) Exponential; ex
log(x) Natural log
log10(x) Base 10 log
log2(x) Base 2 log
real(x) Complex real part
imag(x) Complex imaginary part
conj(x) Complex conjugate
round(x) Rounds to the nearest integer
…
© 2013 Ehsan Ghias-Begloo 36
Trigonometric Functions sin(x) Sine
cos(x) Cosine
tan(x) Tangent
asin(x) Inverse sine
acos(x) Inverse cosine
atan(x) Inverse tangent
sinh(x) Hyperbolic sine
cosh(x) Hyperbolic cosine
tanh(x) Hyperbolic tangent
…
© 2013 Ehsan Ghias-Begloo 37
Trigonometric functions expect their argument to be in radian!
Logical & Relational Operators & AND
| OR
~ NOT
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
~= Not equal to
© 2013 Ehsan Ghias-Begloo 38
Saving figure or model to disk as image or MATLAB file
>> print -dpsc myPlot.ps Postscript
>> print -dwinc Windows printer
>> print –dbitmap Windows bitmap clipboard
>> saveas(gcf, 'myPlot', 'pdf') Save file
© 2013 Ehsan Ghias-Begloo 40
File types: pdf, jpeg, gif, bmp, fig, etc.
Helpful Commands help plot Displays help about “plot” in Command Window helpwin plot Displays help about “plot” in Help Window lookfor plot Searches help for “plot”
clear Clears variables & functions from memory
hold on / off Holds current graph
pause Pauses code & wait for user response, i.e. key
pause(t) Pauses for t seconds & resume afterwards
figure Creates a new figure window
close Closes a figure/window
clc Clears the command window
…
© 2013 Ehsan Ghias-Begloo 41