An Overview of
MATLAB
Cheng-Liang Chen
PSE
LABORATORY
Department of Chemical Engineering National TAIWAN University
Chen CL
1
MATrix LABoratory
Chen CL
1
MATrix LABoratory
Chen CL
2
MATLAB Interactive Sessions
Starting MATLAB Desktop to manage the Command window and a Help Browser
Command window: window: to communicate with the M the MA ATLAB program by typing instructions of various types called commands , functions , and statements
Launch Pad window: window: (file manager window)
⇒
Launch Pad window: window : to list toolboxes and other M other MA ATLAB-related programs (such as Simulink as Simulink)) Current directory Workspace
Command History window: window: to sho show w all the prev reviou iouss keys eystro trokkes entered in the Command the Command window
One can alter the appearance of the Desktop the Desktop
Chen CL
3
An Interactive Session 8/10 ans = 0.800 5*ans ans = 4.000 r = 8/10 r = 0.8000
r r = 0.8000 s = 20*r s = 16 sr = sqrt(s) sr = 4.000
Chen CL
4
Scalar Arithmetic Operations and Order of Precedence Symbol
Operation
^
*
MATLAB Form
exponentiation: ab
a^b
multiplication: ab
a*b
/
right division: a/b =
\
left le ft di divi visi sion on:: a b =
+
-
\
addition: a + + b b subtraction: a
−b
a b b a
a/b a\b a+b a-b
Prec Pr eced eden ence ce
Operat Oper atio ion n
First
Parentheses, evaluated starting with the innermost pair Parentheses,
Second Third Fourth
Exponentiation,, evaluated from left Exponentiation from left to right Multiplication and and division division with with equal precedence (left ( left to right) right)
Addition and and subtraction subtraction with with equal precedence (left ( left to right) right)
Chen CL
5
Scalar Arithmetic Operations and Order of Precedence: Some Examples 8+3*5 ans = 23 8 + (3*5) ans = 23 (8+3)*5 ans = 55 4^2-12-8/4*2 ans = 0 4^2-12-8/(4*2) ans = 3
3*4^2 + 5 ans = 53 (3*4)^2 + 5 ans = 149 27^(1/3) + 32^(0.2) ans = 5 27^(1/3) + 32^0.2 ans = 5 27^1/3 + 32^0.2 ans = 11
Chen CL
6
Test Your Understanding T1.1-1 Use MATLAB to compute the following expressions. 10 18 (a) 6 + + 5(92) 13 5(7) (b)
6 351/4 + 140.35
Chen CL
7
The Assignment Operator
Example 1.1-1 Volume of a circular cylinder The volume of a circular cylinder of height h and radius r is given by V = πr 2h. A particular cylinder tank is 15 meters tall and has a radius of 8 meters. We want to construct another cylinder tank with a volume 20% greater but having the same height. How large must its radius be ?
Solution:
V = πr h
MATLAB Code: pie r = h = V =
2
= 3.1416; 8; 15; pie*r^2*h;
⇒
r=
V πh
V = V + 0.2*V; % new volume r = sqrt(V/(pie*h)) r = 8.7636
Chen CL
8
Variable Names
Variable names must begin with a letter and must contain less than 32 characters MATLAB is case-sensitive speed, Speed, SPEED, speed_1, speed_2
Chen CL
9
Commands for Managing the Work Session Command
Description
clc Clears the command window clear Removes all variables from memory clear var1 var2 Removes var1 and var2 from memory exist(’name’) quit
Determine if a file or variable exists having the name ’name’ Stop MATLAB
who whos
Lists the variables currently in memory Lists the current variables and sizes, and indicates if they have imaginary parts
: ,
Colon; generates an array having regularly spaced elements Comma; separates elements of an array
;
Semicolon; suppresses screen printing; also denotes a new row in an array Ellipsis; continues a line to delay execution
...
Chen CL
10
Managing the Work Session x = 2; y = 6+x, x = y+7 y = 8 x = 15 who Your variables are: x y
whos Name Size Bytes Class x 1x1 8 double array y 1x1 8 double array Grand total is 2 elements using 16 bytes clear who (nothing)
Chen CL
11
Predefined Constants Command
Description
ans
Temporary variable containing the most recent answer
eps i,j
Specifies the accuracy of floating point precision The imaginary unit 1
Inf NaN pi
Inf inity, Indicates an undefined numerical result (Not a Number) The number π
∞
√ −
Chen CL
12
Complex Number Operations s = 3+7i; w+s
w = 5-9i;
ans = 8.0000 - 2.0000i
w*s ans = 78.0000 + 8.0000i w/s ans = -0.8276 - 1.0690i
Chen CL
13
Test Your Understanding T1.1-2 Given x =
−5 + 9i and y = 6 − 2i, use MATLAB to show that x + y = 1 + 7i xy = and
x/y =
−12 + 64i −1.2 + 1.1i
Chen CL
14
Arrays u = [0:2:10]; w = 5*sin(u); u, w
m = length(w) m = 6
u = 0 2 4 6 8 10 w = 0 4.5465 -3.7840 -1.3971 4.9468 -2.7201 u(3), w(3) ans = 4 ans = -3.7840
Chen CL
15
Polynomial Roots
x3
− 7x2 + 40x − 34 = 0 ⇐⇒ roots = 1, 3 ± 5i
a = [1, -7, 40, -34],... roots(a)
r = [1, 3+5i, 3-5i],... poly(r)
a = 1 -7 40 -34 ans = 3.000 + 5.000i 3.000 - 5.000i 1.000
r = 1.00 ans = 1
3.00+5.00i -7
40
3.00-5.00i -34
Chen CL
16
Some Polynomial Functions Command
Description
poly(r)
Computes the coefficients of the polynomial whose roots are specified by the array r. The resulting coefficients are arranged in descending order of powers. Evaluates a polynomial at specified values of its independent variable x. The polynomial’s coefficients of descending powers are stored in the array a. The result is the same size as x. Computes an array containing the roots of a polynomial specified by the coefficient array a.
polyval(a,x)
roots(a)
Chen CL
17
Test Your Understanding T1.3-1 Use MATLAB to determine how many elements are in the array [cos(0):0.02:log10(100)] . Use MATLAB to determine the 25th element. (ANS: 51 elements and 1.48) T1.3-2 Use MATLAB to find the roots of the polynomial 290 6x2 + x3. Use the poly function to verify the solution.
− 11x +
Chen CL
18
Working with Floppy Disks Suppose you have saved the file problem1.m in the directory \homework on a floppy disk which you insert in drive a: When you type problem1
MATLAB first checks to see if problem1 is a variable and if so, displays its value
If not, MATLAB then checks to see if problem1 is one of its own built-in commands , and executes it if it is
If not, MATLAB then looks in the current directory for a file named problem1.m and executes problem1 if it is found
If not, MATLAB then searches the directories in its search path , in order, for problem1.m and then executes it if found
Chen CL
pwd
19
C:\MATLAB6p5p1\work
cd d:\Color-Slides\MATLAB\Palm\DataFiles type test.m % This is my first test M-file fprint(’Start of test.m!\n’) for i = 1:3 fprintf(’i = %d ---> i^3 = %d\n’, i,i^3); end fprintf(’End of test.m!\n’); test
Start of test.m! i = 1 ---> i^3 = 1 i = 2 ---> i^3 = 8 i = 3 ---> i^3 = 27 End of test.m!
Chen CL
20
System, Directory, and File Commands Command
Description
addpath dirname cd dirname dir dir dirname path pathtool pwd
Adds the directory dirname to the search path Changes the current directory to dirname Lists all files in the current directory Lists all the files in the directory dirname Display the MATLAB search path Starts the Path Browser Displays the current directory
rmpath dirname what
Removes directory dirname from search path Lists MATLAB-specific files found in current working directory. Most data files and other non-MATLAB files are not listed. Use dir to get a list of all files Lists the MATLAB-specific files in directory dirname
what dirname
Chen CL
21
Relational Operators x y z z
= = = = 1 z = z = 0
[ 6, 3, 9]; [14, 2, 9]; (x < y) 0 0 (x > y) 1
0
z = (x ~= y) z = 1 1 0 z = (x == y) z = 0 0 1 z = (x > 8) z = 0 0 1
x = [ 6, 3, 9, 11]; y = [14, 2, 9, 13]; values = x(x
x y z z
= [ 6, 3, 9, 11]; = [14, 2, 9, 13]; = x(x
Relational Operator < <= > >= == ~=
Meaning Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to
Chen CL
22
Example: Analysis of Temperature Data The arrays temp_A and temp_B given in the table contain the water temperature in degree Fahrenheit of two ponds measured at noon for 10 days. Determine how many days the temperature of pond A was above 60o. On what days did this occur ? Determine the temperature of pond A on the days when it was greater than or equal to the temperature of pond B. Day 1 Pond A 55 Pond B 54
2 62 59
3 60 62
4 61 64
5 63 68
A=[55,62,60,61,63,65,62,59,58,56]; B=[54,59,62,64,68,68,62,59,57,53]; when = find(A>60) when = 2 4 5 6 7 how_many1 = length(when) how_many1 = 5
6 65 68
7 62 62
8 59 59
9 58 57
10 56 53
above = A(A>=B) above = 55 62 62 59 58 56 how_many2 = length(above) how_many2 = 6
Chen CL
23
Test Your Understanding T1.3-3 Suppose that x = [ 9, 6, 0, 2, 5] and y = [ 10, 6, 2, 4, 6]. What is the result of the following operations ? Determine the answers by hand, and then use MATLAB to check your answers.
− −
− −
(a) z=(xy) (c) z=(x~=y) (d) z=(x==y) (e) z=(x>2) T1.3-4 Suppose that x = [ 4, 1, 0, 2, 10] and y = [ 5, 2, 2, 5, 9]. Use MATLAB to find the values and the indices of the elements in x that are greater than the corresponding elements in y.
− −
− −
Chen CL
24
Plotting with MATLAB 1
0.8
0.6
x = [0 : .01 : 10]; y = sin(2*x); plot(x,y)
0.4
0.2 ) x 2 ( n i s
0
−0.2
xlabel(’x’) ylabel(’sin(2x)’)
−0.4
−0.6
−0.8
−1 0
1
2
3
4
5 x
6
7
8
9
10
Chen CL
25
Overlay Plot 5
x = [0 : .01 : 5]; y = 2*sqrt(x); z = 4*sin(3*x);
4
3
2sqrt(x)
2
1
plot(x,y, x,z) xlabel(’x’) gtext(’2sqrt(x)’) gtext(’4sin(3x)’)
4sin(3x)
0
−1
−2
−3
−4
0
0.5
1
1.5
2
2.5 x
3
3.5
4
4.5
5
Chen CL
26
Data Marker 90
80
x = [15 : 2 : 23]; y = [20, 50, 60, 90, 70]; plot(x,y,’+’,x,y,’--’) % plot(x,y,’+--’) xlabel(’x (seconds)’) ylabel(’y (volts)’)
70
) s t l
60
o v ( y
50
40
30
20 15
16
17
18
19 x (seconds)
20
21
22
23
Chen CL
27
Plotting Polynomials 1200
1000
a = [9, -5, 3, 7]; x = [-2 : .01 : 5]; f = polyval(a,x); plot(x,f) xlabel(’x’), ylabel(’f(x)’) grid
800
600 ) x ( f
400
200
0
−200 −2
−1
0
1
2 x
3
4
5
Chen CL
28
Some MATLAB Plotting Commands Command
Description
[x,y]=ginput(n)
Enables the mouse to get n points from a plot, and returns the x and y, which have a length n. Puts grid lines on the plot. Enables placement of text with the mouse.
grid gtext(’text’) plot(x,y)
title(’text’)
Generates a plot of the array y versus the array x on rectilinear axes. Evaluates a polynomial at specified values of its independent variable x. The polynomial’s coefficients of descending powers are stored in the array a. The result is the same size as x. Puts text in a title at the top of the plot.
xlabel(’text’) ylabel(’text’)
Adds a text label to the horizontal axis (the abscissa). Adds a text label to the vertical axis (the ordinate).
polyval(a,x)
Chen CL
29
Test Your Understanding T1.3-5 Use MATLAB to plot the function s = 2sin(3t + 2) + 5t + 1 over the interval 0 t 5. Put a title on the plot, and properly label the axes. The variable s represents speed in feet per second; The variable t represents time in seconds.
√
≤ ≤
T1.3-6 Use MATLAB to plot the function y = 4 6x + 1 and z = 4x3 + 6x2 5x + 3 over the interval 0 x 1.5. Properly label the plot and each curve. The variables y and z represent force in newtons; the variable x represents distance in meters.
√
−
≤ ≤
Chen CL
30
Linear Algebraic Equations 6x + 12y + 4z = 70 7x
− 2y + 3z 2x + 8y − 9z
= 5 = 64
⇓ − − 6 12 7 2
4
2
3
8
9
A
or
x
A = [6,12,4; 7,-2,3; 2,8,-9]; B = [70; 5; 64]; A, B, Solution = A\B A = 6 12 4 7 -2 3 2 8 -9
70
=
y
5
z
64
x
B
A x
x
=
⇓
=
B
A−1B
B = 70 5 64 Solution = 3 5 -2
Chen CL
31
Test Your Understanding T1.3-7 Use MATLAB to solve the following set of equations. 6x
− 4y + 8z = 112 −5x − 3y + 7z = 75 14x + 9y − 5z = −67 (ANS: x = 2, y =
−5, z = 10)
Chen CL
32
Script Files and Editor/Debugger Perform operations in MATLAB in two ways: 1. In the interactive mode : all commands are entered directly in the Command window, or 2. Write and save MATLAB programs in a M-file (script or command file containing a sequence of MATLAB commands), and then execute it at the Command window (a) script file (b) function file Advantage: TO avoid the need to retype commonly used procedures or complex commands
Chen CL
33
Creating and Using A Script File
Use any text editor to create a new M (script) file, or Use the Editor/Debugger: File New M-File
⇒
% % % % x y
⇒
⇒
Select a current directory File Save PalmP33.m
⇒
Program PalmP33.m This program computes the sine of the square root, and displays the results = sqrt([3:2:11]); = sin(x)
Type PalmP33 to execute the program y = 0.9870
0.7867
0.4758
0.1411
-0.1741
Chen CL
34
Effective Use of Script Files
Name: follows the MATLAB convention for naming variables (begin with a letter, up to 31 characters, don’t use ”-”, )
···
Don’t give a script file the same name as a variable it computes Note: typing a variable’s name at Command window prompt causes MATLAB to display variable’s value
⇒ MATLAB will not be able to execute this script file more than once (unless clear the variable)
Don’t give a script file the same name as a MATLAB command or function exist(’PalmP33’) 0 if a variable PalmP33 does not exist 0 if a file PalmP33.m does not exist exist(’PalmP33.m’,’file’) 0 if a built-in function PalmP33 does not exist exist(’PalmP33’,’builtin’)
⇒
⇒ ⇒
Chen CL
35
Effective Use of Script Files
All variables created by a script file are global variables All variables created by a function file are local variables Use type PalmP33 to view this M-file Using script files to store data (PalmP38.m) % File MyData.m: store temperature data % Stores the array temp_F % which contains temperatures in degrees Fahrenheit temp_F = [72, 68, 75, 77, 83, 79]
PalmP38
temp_F = 72
68
75
77
83
79
Chen CL
36
Conditional Statements
√ y= x
for x > 0
if x > 0 y = sqrt(x) end
y=
√ x √ − −x
for x > 0 for x < 0
if x > 0 y = sqrt(x) else y = -sqrt(-x) end
y=
√
50 x for x 25 10x for 25 > x 0
≥
others
if x >= 25 y = 50*sqrt(x) elseif x >= 0 y = 10*x else y = 0 end
≥0
Chen CL
37
Loops m = 0; x(m+1) = 10; for k = 2:3:11 m = m+1 x(m+1) = x(m) + k^2 end x x = 10 14 39 103 224
m = 1; k = -1; x(m) = 10; while x(m) < 200 k = k+3; m = m+1; x(m) = x(m-1) + k^2; end x x = 10 14 39 103 224
Com. Description else Delineates an alternate block of commands elseif Conditional executes an alternate block of commands end Terminates for, while and if statements find(x) Gives an array for indices with nonzero elements for Repeats commands a specified number of times if Executes commands conditionally while Repeats commands an indefinite number of times
Chen CL
38
Example: Growth of A Bank Account Determine how long it will take to accumulate at least $10, 000 in a bank account it you deposit $500 initially and $500 at the end of each year, if the account pays 5 percent annual interest. amount = 500; k=0; while amount < 10000 k = k+1; amount = amount*1.05 + 500; end amount k
amount = 1.0789e+004 k = 14
% 10,789
Chen CL
39
Some MATLAB Programming Statements
Command Description else
Delineates an alternate block of commands
elseif
Conditionally executes an alternate block of commands
end
Terminates for, while, and if statements
find(x)
Computes an array containing the indices of the nonzero elements of the array x
for
Repeats commands a specified number of times
if
Executes commands conditionally
while
Repeats commands an indefinite number of times
Chen CL
40
Testing Your Understanding T1.4-1 Create, save, and run a script file that solves the following set of equations for given values of a, b, and c. Check your file for the case a = 112, b = 75, c = 67 (answer: x = 2, y = 5, z = 10).
−
−
6x 5x
− 4y + 8z − − 3y + 7z 14x + 9y − 5z
= a = b = c
T1.4-2 Write a script file using conditional statements to evaluate the following function, assuming that the scalar variable x has a value of 5, 5, 15, respectively.
−
√
x2 + 1
y=
3x + 1 9 sin(5x
for x < 0
−
for 0 50) + 31 for x
≤ x < 10 ≥ 10
Chen CL
41
Testing Your Understanding T1.4-3 Use a for loop to determine the sum of the first 20 terms in the series 3k2, k = 1, 2, . . . , 20 (Ans: 8610). T1.4-4 Use a while loop to determine how many terms in the series 3k2, k = 1, 2, . . . are required for the sum of the terms to exceed 2000. What is the sum of this number of terms (Ans: 13 terms, a sum of 2457).
Chen CL
42
The MATLAB Help System
help FunctionName help log10 LOG10 Common (base 10) logarithm. LOG10(X) is the base 10 logarithm of the elements of X. Complex results are produced if X is not positive. See also LOG, LOG2, EXP, LOGM.
lookfor KeyWord lookfor sine ACOS Inverse cosine. ACOSH Inverse hyperbolic cosine. ASIN Inverse sine. ASINH Inverse hyperbolic sine. ... ... ... ...
Chen CL
43
The MATLAB Help System
doc Name doc function
Display the documentation for the MATLAB function function
Chen CL
44
Problem-Solving Methodologies Suppose you work for a company that produces packaging. You are told that a new packaging material can protect a package when dropped, provided that the package hits the ground at less than 25 feet per second. The package’s total weight is 20 pounds, and it is rectangular with dimensions of 12 by 12 by 8 inches. You must determine whether the packaging material provides enough protection when the package is carried by delivery persons.
1. Understand the purpose of the problem. The implication here is that the packaging is intended to protect against being dropped while the delivery person is carrying it.
2. Collect the known information. The known information is the package’s weight, dimension, and maximum allowable impact speed.
Chen CL
45
Problem-Solving Methodologies 3. Determine what information you must find. You need to determine the maximum height from which the package can be dropped without damage. You need to find a relationship between the speed of impact and the height at which the package is dropped.
4. Simplify the problem; State assumptions. The package is dropped from rest with no vertical or horizontal velocity The package is not tumble (as it might when dropped from a moving truck) The effect of air drag is negligible The greatest height the delivery person could drop the package from is 6 ft The acceleration g due to gravity is constant
Chen CL
46
Problem-Solving Methodologies 5. Draw a sketch and label necessary variables.
6. Determine what fundamental principles are applicable. Newton’s law h = 12 gt 2i Height versus time to impact: vi = gti Impact speed vi versus time to impact: mgh = 12 mvi2 Conservation of mechanical energy:
Chen CL
47
Problem-Solving Methodologies 7. Think generally about your proposed solution. The most efficient approach is to solve the third relation for h 1 vi2 h = 2g The mass does not affect the relation between the impact speed and the height dropped
8. Label each step in the solution process. 2
1 vi 2 g
Basic principle: conservation of mechanical energy h = 2 Determine the value of constant g: g = 32.2 ft/sec 2 1 25 = 9.7 ft Use given information to perform the calculation: h = 2 32.2
g = 32.2; vi = 25; h = vi^2/(2*g)
h = 9.7050
Chen CL
48
Problem-Solving Methodologies 9. Check the dimensions and units.
1 [ft/sec]2 [ft]2 [sec]2 [ft] = = = [ft] 2 2 2 [ft/sec ] [sec] [ft]
10. Perform reality and precision check on answer. The computed height of 9.7 feet does not seem unreasonable
Conclusion: 9.7 feet > 6 feet (deliver person’s height)
⇒ the packaging material can provide enough protection
Chen CL
49
Steps in Generating A Computer Solution The following figure shows a piston, connecting rod, and crank for an internal combustion engine. When combustion occurs, it pushes the piston down. This motion causes the connecting rod to turn the crank, which causes the crankshaft to rotate. We want to develop a MATLAB program to compute and plot the distance d traveled by the piston as a function of the angle A, for given values of the lengths L1 and L2. Such a plot would help the engineers designing the engine to select appropriate values for the lengths L1 and L2. We are told that typical values for those lengths are L1 = 1 and L2 = 0.5 foot. Because the mechanism’s motion is symmetrical about A = 0, we need consider only angles in the range 0 A 180o.
≤ ≤
Solution:
Chen CL
50
Steps in Generating A Computer Solution
1. State problem concisely.
L1 sin(B) = L2 sin(A) L2 sin(B) = sin(A) L1 L2 sin(A) B = sin−1 L1 d = L1 cos(B) + L2 cos(A)
⇒
2. Specify the input data to be used by the program. The lengths of L1, L2, and A are given
3. Specify the output to be generated by the program. A plot of d versus A is the required output A (degree)
4. Work through the solution steps by hand or with a calculator.
d (feet)
0
1.50
60 90 120 180
1.15 0.87 0.65 0 50
d = L 1 + L2 d =
−
d
L
L21
L
L22
Chen CL
51
Steps in Generating A Computer Solution 5. Write and run the program. 1.5
L_1 = 1; L_2 = .5; R = L_2/L_1; A_d = [0:.5:180]; A_r = A_d*(pi/180); B = asin(R*sin(A_r)); d = L_1*cos(B) + L_2*cos(A_r); plot(A_d,d) xlabel(’A (degrees)’) ylabel(’d (feet)’), grid
1.4
1.3
1.2
1.1 ) t e e f (
1
d
0.9
0.8
0.7
0.6
0.5 0
20
40
60
80 100 A (degrees)
120
6. Check the output of the program with your hand solution. 7. Run the program and perform a reality check on the output. 8. Test the program for a range of reasonable input values.
140
160
180
Chen CL
52
Some Special Symbols and Functions Symbol %
Functions asin(x) cos(x) exp(x) length(x) log(x) log10(x) mean(x) sin(x) sqrt(x) std(x)
Use Designates a comment Use Compute the inverse sine of x Compute the cosine of x
sin−1(x) cos(x)
Compute the exponential of x Compute the # of elements in array x Compute the natural logarithm of x
ex
Compute the base-10 logarithm of x Compute the mean of x
log10(x)
Compute the sine of x Compute the square root of x
sin(x) x
Compute the standard deviation of x
ln(x)
√