Sei sulla pagina 1di 54

An Overview of

MATLAB
Cheng-Liang Chen
PSE
LABORATORY
Department of Chemical Engineering
National TAIWAN University
Chen CL 1
MATrixLABoratory
Chen CL 2
MATLAB Interactive Sessions
Starting MATLAB Desktop
to manage the Command window and a Help Browser
Command window: to communicate with the MATLAB program
by typing instructions of various types called commands, functions,
and statements
Launch Pad window: (le manager window)
Launch Pad window: to list toolboxes and other MATLAB-related programs
(such as Simulink)
Current directory
Workspace
Command History window: to show all the previous keystrokes
entered in the Command window
One can alter the appearance of 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: a
b
a^b
* multiplication: ab a*b
/ right division: a/b =
a
b
a/b
\ left division: a\b =
b
a
a\b
+ addition: a + b a+b
- subtraction: a b a-b
Precedence Operation
First Parentheses, evaluated starting with the innermost pair
Second Exponentiation, evaluated from left to right
Third Multiplication and division with equal precedence (left to right)
Fourth Addition and subtraction with equal precedence (left to 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.
(a) 6
10
13
+
18
5(7)
+ 5(9
2
)
(b) 6
_
35
1/4
_
+ 14
0.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
2
h.
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
2
h r =
_
V
h
MATLAB Code:
pie = 3.1416;
r = 8;
h = 15;
V = pie*r^2*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) Determine if a le or variable exists having the name name
quit Stop MATLAB
who Lists the variables currently in memory
whos 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
Predened Constants
Command Description
ans Temporary variable containing the most recent answer
eps Species the accuracy of oating point precision
i,j The imaginary unit

1
Inf Infinity,
NaN Indicates an undened numerical result (Not a Number)
pi The number
Chen CL 12
Complex Number Operations
s = 3+7i; w = 5-9i;
w+s
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 = 12 + 64i
and x/y = 1.2 + 1.1i
Chen CL 14
Arrays
u = [0:2:10];
w = 5*sin(u);
u, w
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
m = length(w)
m =
6
Chen CL 15
Polynomial Roots
x
3
7x
2
+ 40x 34 = 0 roots = 1, 3 5i
a = [1, -7, 40, -34],...
roots(a)
a =
1 -7 40 -34
ans =
3.000 + 5.000i
3.000 - 5.000i
1.000
r = [1, 3+5i, 3-5i],...
poly(r)
r =
1.00 3.00+5.00i 3.00-5.00i
ans =
1 -7 40 -34
Chen CL 16
Some Polynomial Functions
Command Description
poly(r) Computes the coecients of the polynomial whose roots
are specied by the array r. The resulting coecients are
arranged in descending order of powers.
polyval(a,x) Evaluates a polynomial at specied values of its independent
variable x. The polynomials coecients of descending
powers are stored in the array a. The result is the same size
as x.
roots(a) Computes an array containing the roots of a polynomial
specied by the coecient array 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 25
th
element.
(ANS: 51 elements and 1.48)
T1.3-2
Use MATLAB to nd the roots of the polynomial 290 11x +
6x
2
+ x
3
. Use the poly function to verify the solution.
Chen CL 18
Working with Floppy Disks
Suppose you have saved the le problem1.m in the directory
\homework on a oppy disk which you insert in drive a:
When you type problem1
MATLAB rst 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 le
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 19
pwd 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 Adds the directory dirname to the search path
cd dirname Changes the current directory to dirname
dir Lists all les in the current directory
dir dirname Lists all the les in the directory dirname
path Display the MATLAB search path
pathtool Starts the Path Browser
pwd Displays the current directory
rmpath dirname Removes directory dirname from search path
what Lists MATLAB-specic les found in current working
directory. Most data les and other non-MATLAB les are
not listed. Use dir to get a list of all les
what dirname Lists the MATLAB-specic les in directory dirname
Chen CL 21
Relational Operators
x = [ 6, 3, 9];
y = [14, 2, 9];
z = (x < y)
z =
1 0 0
z = (x > y)
z =
0 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];
z = x(x<y)
z =
[6, 11]
x = [-2, 0, 4];
y = find(x) % (indices
% with nonzero elements)
y =
1 3
x = [ 6, 3, 9, 11];
y = [14, 2, 9, 13];
values = x(x<y)
values =
6 11
how_many = length(values)
how_many =
2
indices = find(x<y)
indices =
1 4
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 60
o
. 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 2 3 4 5 6 7 8 9 10
Pond A 55 62 60 61 63 65 62 59 58 56
Pond B 54 59 62 64 68 68 62 59 57 53
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
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=(x<y)
(b) z=(x>y)
(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 nd 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
x = [0 : .01 : 10];
y = sin(2*x);
plot(x,y)
xlabel(x)
ylabel(sin(2x))
0 1 2 3 4 5 6 7 8 9 10
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
x
s
i
n
(
2
x
)
Chen CL 25
Overlay Plot
x = [0 : .01 : 5];
y = 2*sqrt(x);
z = 4*sin(3*x);
plot(x,y, x,z)
xlabel(x)
gtext(2sqrt(x))
gtext(4sin(3x))
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
4
3
2
1
0
1
2
3
4
5
x
2sqrt(x)
4sin(3x)
Chen CL 26
Data Marker
x = [15 : 2 : 23];
y = [20, 50, 60, 90, 70];
plot(x,y,+,x,y,--)
% plot(x,y,+--)
xlabel(x (seconds))
ylabel(y (volts))
15 16 17 18 19 20 21 22 23
20
30
40
50
60
70
80
90
x (seconds)
y

(
v
o
l
t
s
)
Chen CL 27
Plotting Polynomials
a = [9, -5, 3, 7];
x = [-2 : .01 : 5];
f = polyval(a,x);
plot(x,f)
xlabel(x), ylabel(f(x))
grid
2 1 0 1 2 3 4 5
200
0
200
400
600
800
1000
1200
x
f
(
x
)
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.
grid Puts grid lines on the plot.
gtext(text) Enables placement of text with the mouse.
plot(x,y) Generates a plot of the array y versus the array x on rectilinear
axes.
polyval(a,x) Evaluates a polynomial at specied values of its independent
variable x. The polynomials coecients of descending powers are
stored in the array a. The result is the same size as x.
title(text) Puts text in a title at the top of the plot.
xlabel(text) Adds a text label to the horizontal axis (the abscissa).
ylabel(text) Adds a text label to the vertical axis (the ordinate).
Chen CL 29
Test Your Understanding
T1.3-5
Use MATLAB to plot the function s = 2 sin(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 =
4x
3
+ 6x
2
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 = 5
2x + 8y 9z = 64

_
6 12 4
7 2 3
2 8 9
_

_
. .
A
_

_
x
y
z
_

_
..
x
=
_

_
70
5
64
_

_
. .
B
or A x = B

x = A
1
B
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
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-le (script or command
le containing a sequence of MATLAB commands), and then
execute it at the Command window
(a) script le
(b) function le
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) le, or
Use the Editor/Debugger: Select a current directory
File New M-File File Save PalmP33.m
% Program PalmP33.m
% This program computes the sine of the square root,
% and displays the results
%
x = sqrt([3:2:11]);
y = sin(x)
Type PalmP33 to execute the program
y =
0.9870 0.7867 0.4758 0.1411 -0.1741
Chen CL 34
Eective Use of Script Files
Name: follows the MATLAB convention for naming variables
(begin with a letter, up to 31 characters, dont use -, )
Dont give a script le the same name as a variable it computes
Note: typing a variables name at Command window prompt causes MATLAB
to display variables value
MATLAB will not be able to execute this script le more than once
(unless clear the variable)
Dont give a script le the same name as a MATLAB command
or function
exist(PalmP33) 0 if a variable PalmP33 does not exist
exist(PalmP33.m,le) 0 if a le PalmP33.m does not exist
exist(PalmP33,builtin) 0 if a built-in function PalmP33 does not exist
Chen CL 35
Eective Use of Script Files
All variables created by a script le are global variables
All variables created by a function le are local variables
Use type PalmP33 to view this M-le
Using script les 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 for x > 0

x 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
0 others
if x >= 25
y = 50*sqrt(x)
elseif x >= 0
y = 10*x
else
y = 0
end
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
nd(x) Gives an array for indices with nonzero elements
for Repeats commands a specied number of times
if Executes commands conditionally
while Repeats commands an indenite 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 % 10,789
k =
14
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
nd(x) Computes an array containing the indices of the nonzero
elements of the array x
for Repeats commands a specied number of times
if Executes commands conditionally
while Repeats commands an indenite number of times
Chen CL 40
Testing Your Understanding
T1.4-1
Create, save, and run a script le that solves the following set of equations for
given values of a, b, and c. Check your le for the case a = 112, b = 75, c = 67
(answer: x = 2, y = 5, z = 10).
6x 4y + 8z = a
5x 3y + 7z = b
14x + 9y 5z = c
T1.4-2
Write a script le using conditional statements to evaluate the following function,
assuming that the scalar variable x has a value of 5, 5, 15, respectively.
y =
_

x
2
+ 1 for x < 0
3x + 1 for 0 x < 10
9 sin(5x 50) + 31 for x 10
Chen CL 41
Testing Your Understanding
T1.4-3
Use a for loop to determine the sum of the rst 20 terms in the series
3k
2
, k = 1, 2, . . . , 20 (Ans: 8610).
T1.4-4
Use a while loop to determine how many terms in the series 3k
2
, 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 packages 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 packages weight, dimension, and maximum
allowable impact speed.
Chen CL 45
Problem-Solving Methodologies
3. Determine what information you must nd.
You need to determine the maximum height from which the package can be
dropped without damage. You need to nd 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 eect 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.
Newtons law
Height versus time to impact: h =
1
2
gt
2
i
Impact speed v
i
versus time to impact: v
i
= gt
i
Conservation of mechanical energy: mgh =
1
2
mv
2
i
Chen CL 47
Problem-Solving Methodologies
7. Think generally about your proposed solution.
The most ecient approach is to solve the third relation for h
h =
1
2
v
2
i
g
The mass does not aect the relation between the impact speed and the height
dropped
8. Label each step in the solution process.
Basic principle: conservation of mechanical energy h =
1
2
v
2
i
g
Determine the value of constant g: g = 32.2 ft/sec
2
Use given information to perform the calculation: h =
1
2
25
2
32.2
= 9.7 ft
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.
[ft] =
_
1
2
_
[ft/sec]
2
[ft/sec
2
]
=
[ft]
2
[sec]
2
[sec]
2
[ft]
= [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 persons height)
the packaging material can provide enough protection
Chen CL 49
Steps in Generating A Computer Solution
The following gure 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 L
1
and L
2
. Such a plot would help the engineers
designing the engine to select appropriate values
for the lengths L
1
and L
2
.
We are told that typical values for those lengths are L
1
= 1 and L
2
= 0.5 foot.
Because the mechanisms motion is symmetrical about A = 0, we need consider
only angles in the range 0 A 180
o
.
Solution:
Chen CL 50
Steps in Generating A Computer Solution
1. State problem concisely.
L
1
sin(B) = L
2
sin(A)
sin(B) =
L
2
L
1
sin(A)
B = sin
1
_
L
2
sin(A)
L
1
_
d = L
1
cos(B) + L
2
cos(A)
2. Specify the input data to be
used by the program.
The lengths of L
1
, L
2
, and A are
given
3. Specify the output to be
generated by the program.
A plot of d versus A is the required
output
4. Work through the solution
steps by hand or with a calculator.
A (degree) d (feet)
0 1.50 d = L
1
+ L
2
60 1.15
90 0.87 d =
_
L
2
1
L
2
2
120 0.65
180 0.50 d = L
1
L
2
Chen CL 51
Steps in Generating A Computer Solution
5. Write and run the program.
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
0 20 40 60 80 100 120 140 160 180
0.5
0.6
0.7
0.8
0.9
1
1.1
1.2
1.3
1.4
1.5
A (degrees)
d

(
f
e
e
t
)
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.
Chen CL 52
Some Special Symbols and Functions
Symbol Use
% Designates a comment
Functions Use
asin(x) Compute the inverse sine of x sin
1
(x)
cos(x) Compute the cosine of x cos(x)
exp(x) Compute the exponential of x e
x
length(x) Compute the # of elements in array x
log(x) Compute the natural logarithm of x ln(x)
log10(x) Compute the base-10 logarithm of x log
10
(x)
mean(x) Compute the mean of x
sin(x) Compute the sine of x sin(x)
sqrt(x) Compute the square root of x

x
std(x) Compute the standard deviation of x
Chen CL 53
Thank You for Your Attention
Questions Are Welcome

Potrebbero piacerti anche