matlab for engineers chapter 1 an overview of matlab
TRANSCRIPT
MATLAB for Engineers
Chapter 1An Overview Of MATLAB
WHAT YOU WILL LEARN
Identify the built in function, syntax and notation in MATLAB
Construct script files for execution of mathematical calculations
Produce a program by using loops and conditional statements.
ASSESSMENTTest (s) 20
Assignment(s) /Quiz (s) 30
Final Exam 50
REFERENCE1. Palm, W.J., 2005. Introduction to Matlab 7 for Engineers, McGraw-Hill, New York.2. Hanselman et al., 2005. Mastering MATLAB 7, Pearson Education Inc, New Jersey.3. Amos, G., 2004. MATLAB: An Introduction with Application, 2nd Ed, John Wiley Inc, USA. 4. Moore, H., 2007. MATLAB for Engineers, 2nd Ed., Prentice Hall, New Jersey.
MATLAB WINDOWS
The default view when opening MATLAB includes
1) current folder window
2) command window
3) workspace window
4) command history window
DESCRIPTION
1. Current folder window list all the files in the active directory.
2. Command window use to write and execute MATLAB code
3. Workspace window keeps track of the variables you have defined as you execute them in command window
4. Command history records the command you issued in command window
COMMAND WINDOW
User can perform calculation in a manner similar to scientific calculator
The syntax is almost the same
For example
5^2
ans =
25
>> cos(pi)
ans =
-1
COMMAND HISTORY WINDOWAllow user to review previous MATLAB command
It can be used to transfer previous command to command window
User can transfer any command by double clicking or dragging the line of code into the command window
Try double clicking 5^2
Drag cos(pi) to command window
WORKSPACE WINDOW
oKeeps track of the variables user have defined when execute command in command window
oNow user probably has only one variables which is ans with value of 25
oTo add variables, type A=5 in command window
oObserve the changes to workspace window
oFor now, user can enter a simple one-dimensional matrix by typing
>> b=[1,2,3,4]
b =
1 2 3 4
oNotice that variable b has been added to the workspace with array of 1x4
DIARY
Diary function allow user to record MATLAB command window session file and retrieve it for later review. To activate simply type in command window
diary on
A file diary should appear in the current folder and user may open the file using Notepad.
All record will only be shown after closing MATLAB program
WORKSPACE WINDOW
oNow user defined a two-dimensional matrix as follow
> c=[1,2,3,4;5,6,7,8;9,10,11,12]
c =
1 2 3 4
5 6 7 8
9 10 11 12
oNotice that c appears in the workspace window as a 3x4 matrix
ENTERING COMMANDS AND EXPRESSIONS
MATLAB retains your previous keystrokes.
Use the up-arrow key to scroll back back through the commands.
Press the key once to see the previous entry, and so on.
Use the down-arrow key to scroll forward. Edit a line using the left- and right-arrow keys the Backspace key, and the Delete key.
Press the Enter key to execute the command.
All variables must start with a letter i.e. A1, function1 and limit to 63 characters
1-3
1-5
Symbol Operation MATLAB form
^ exponentiation: ab a^b
* multiplication: ab a*b
/ right division: a/b a/b
\ left division: b/a a\b
+ addition: a + b a + b
- subtraction: a - b a - b
An Example Session
>> 8/10ans = 0.8000>> 5*ansans = 4>> r=8/10r = 0.8000>> rr = 0.8000>> s=20*rs = 161-4
MATRICES IN MATLAB
A single value is a scalar which has 1x1 matrix
A list of values arranged either a column or a row is a one-dimensional matrix called a vector
A table of values is represented by a two-dimensional matrix
MATLAB can also handle higher order of arrays for instances 5x5 matrix
Fyi: matrix and arrays refer to the same thing by MATLAB user
Order of Operations
1-6
Precedence Operation
First Parentheses, evaluated starting with the innermost pair.
Second Exponentiation, evaluated from left to right.
Third Multiplication and division with equal precedence, evaluated from left to right.
Fourth Addition and subtraction with equal precedence, evaluated from left to right.
Examples of Precedence
>> 8 + 3*5ans = 23>> 8 + (3*5)ans = 23>>(8 + 3)*5ans = 55>>4^2 12 8/4*2ans = 0>>4^2 12 8/(4*2)ans = 31-7 (continued …)
Examples of Precedence (continued)
>> 3*4^2 + 5ans = 53>>(3*4)^2 + 5ans = 149>>27^(1/3) + 32^(0.2)ans = 5>>27^(1/3) + 32^0.2ans = 5>>27^1/3 + 32^0.2ans = 11
1-8
EXAMPLE
Height of a cylinder is 10cm with radius of 5cm. Find the surface area.
471.2389
THE ASSIGNMENT OPERATOR =
Typing x = 3 assigns the value 3 to the variable x.
We can then type x = x + 2. This assigns the value 3 + 2 = 5 to x. But in algebra this implies that 0 = 2.
In algebra we can write x + 2 = 20, but in MATLAB we cannot.
In MATLAB the left side of the = operator must be a single variable.
The right side must be a computable value.
1-9
EXAMPLE Wind tunnels play an important role in our study of the behavior of high‐performance aircraft. In order to interpret wind tunnel data, engineers need to understand how gases behave. The basic equation describing the properties of gases is the ideal gas law, a relationship studied in detail in freshman chemistry classes. The law states that
whereP = pressure in kPa,V = volume in m3,N = number of kmoles of gas in the sample,R = ideal gas constant, 8.314 kPa m3/kmol K, andT = temperature, expressed in kelvins (K).
In addition, we know that the number of kmoles of gas is equal to the mass of the gas divided by the molar mass (also known as the molecular weight) or
where,m = mass in kg andMW = molar mass in kg/kmol.
Now suppose you know that the volume of air in the wind tunnel is 1000 m3. Before the wind tunnel is turned on, the temperature of the air is 300 K, and the pressure is 100 kPa. The average molar mass (molecular weight) of air is approximately 29 kg/kmol. Find the mass of the air in the wind tunnel.
Commands for managing the work session
1-10
Command Description
clc Clears the Command window.
clear Removes all variables from memory.
clear v1 v2 Removes the variables v1 and v2 from memory.
exist(‘var’)Determines if a file or variable exists having the name ‘var’.
quit Stops MATLAB.
Commands for managing the work session
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.
1-11
Special Variables and Constants
1-12
Command Description
ans Temporary variable containing the most recent answer.
eps Specifies the accuracy of floating point precision.
i,j The imaginary unit -Ö 1.
Inf Infinity.
NaN Indicates an undefined numerical result.
pi The number p.
SPECIAL VARIABLE AND CONSTANT Inf= infinity Example: try typing 5/0=? In Mathlab
NaN= undefined numerical result Example: try typing 0/0=?
Eps= smallest number which when add to 1 will create number greater than 1. Use eps for indicator of accuracy. Example: try x=1+eps, y=1, prove by (x>y) and (x<y)
Complex Number Operations
• The number c1 = 1 – 2i is entered as follows: c1 = 1- 2i.
• An asterisk (*) is not needed between i or j and a number, although it is required with a variable, such as c2 = 5 i*c1.
• Be careful. The expressions y = 7/2*i
and x = 7/2i
give two different results: y = (7/2)i = 3.5iand x = 7/(2i) = –3.5i.
1-13
TEST YOUR UNDERSTANDING 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
Numeric Display Formats
1-14
Command Description and Example
format short Four decimal digits (the default); 13.6745.
format long 16 digits; 17.27484029463547.
format short e Five digits (four decimals) plus exponent; 6.3792e+03.
format long e 16 digits (15 decimals) plus exponent; 6.379243784781294e–
04.
Arrays
• The numbers 0, 0.1, 0.2, until 10 can be assigned to the variable u by typing u = [0:0.1:10].
• To compute w = 5 sin u for u = 0, 0.1, 0.2, …, 10, the session is;
>>u = [0:0.1:10] >>w = 5*sin(u)
• The single line, w = 5*sin(u), computed the formulaw = 5 sin u 101 times.
1-15
Array IndexTo find specific value in array
>>u(7)ans = 0.6000>>w(7)ans = 2.8232
• Use the length function to determine how many values are in an array.
>>m = length(w)m = 101
1-16 More? See pages 19-20.
ARRAY OPERATION
If user want MATLAB to calculate spacing between elements, user may use the linspace command. Specify the initial value, final value and how many values needed.
d= linspace(1,10,3)
To create logarithmically spaced vector with the logspace command. The first two values are powers of 10 represent initial and final values.
E=logspace (1,3,6)
Important to note that value 1 and 3 are 10^1 and 10^3.
MATRICES OPERATION
Matrix addition and subtraction can be used directly with their operator
A=[1 2 3]
B=A+5
Multiplication and division are little different where user need to add dot before operator. This case is for array multiply/divide by an array.
A.*B
A./B
For scalar multiply/divide an array, user may use either (* or .*)
EXERCISE
ARRAY EXERCISE
Use MATLAB to determine how many elements are in the array start with cos(0), increment 0.02 until log10(100). Then, use MATLAB to determine the 25th element.
Answer: 51 element and 1.48
TRANSPOSITION
Transpose operator changes rows to column and vice versa.
Degrees=[10 15 70 90]
Degrees’
To create tables
Radian=[12 12 12 12]
Table=[Degrees’,Radians’]
EXAMPLE Scientific data, such as data collected from wind tunnels, is usually in SI (Système International) units. However, much of the manufacturing infrastructure in the United States has been tooled in English (sometimes called American Engineering or American Standard) units. Engineers need to be fluent in both systems and should be especially careful when sharing data with other engineers. Perhaps the most notorious example of unit confusion problems is the Mars Climate Orbiter, which was the second flight of the Mars Surveyor Program. The spacecraft burned up in the orbit of Mars in September of 1999 because of a lookup table embedded in the craft’s software. The table, probably generated from wind-tunnel testing, used pounds force (lbf) when the program expected values in newtons (N). In this example, we’ll use MATLAB® to create a conversion table of pounds force to newtons. The table will start at 0 and go to 1000 lbf, at 100-lbf intervals. The conversion factor is
1 lbf = 4.4482216 N
Polynomial Roots
To find the roots of x3 – 7x2 + 40x – 34 = 0, the session is
>>a = [1,-7,40,-34];>>roots(a)ans = 3.0000 + 5.000i 3.0000 - 5.000i 1.0000
The roots are x = 1 and x = 3 ± 5i.
1-17
POLYNOMIAL EXERCISE
Use MATLAB to find the roots of the polynomial 290-11x+6x2+x3.
Answer: x=-10 and 2 ± 5i
Some Commonly Used Mathematical Functions
1-18
Function MATLAB syntax1
ex exp(x)
√x sqrt(x)
ln x log(x)
log10 x log10(x)
cos x cos(x)
sin x sin(x)
tan x tan(x)
cos-1 x acos(x)
sin-1 x asin(x)
tan-1 x atan(x)
1The MATLAB trigonometric functions use radian measure.
MATLAB plotting commands
plot(x,y) Generates a plot of the array y versus the array x on rectilinear axes.
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).
1-25
MATLAB plotting commands
1-24
Command Description[x,y] = ginput(n) Enables the mouse to get n points
from a plot, and returns the x and y coordinates in the vectors x and y, which have a length n.
grid Puts grid lines on the plot.
gtext(’text’) Enables placement of text with the mouse.
A graphics window showing a plot.
1-23
X=[0: 0.02: 8]Y=5*sin(x)Plot (x,y) and label x and y-axis
TEST YOU UNDERSTANDING BY
Answer: >> t=[0:5]; >> s=2*sin(3*t+2)+sqrt(5*t+1); >> plot (t,s),xlabel('x (s)'), ylabel('y(ft/s)'),title('speed vs time')
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50
1
2
3
4
5
6
7
x (s)
y(ft
/s)
speed vs time
Solution of Linear Algebraic Equations
6x + 12y + 4z = 707x – 2y + 3z = 52x + 8y – 9z = 64
>>A = [6,12,4;7,-2,3;2,8,-9];>>B = [70;5;64];>>Solution = A\BSolution = 3 5 -2
The solution is x = 3, y = 5, and z = –2.
1-26
TRY THIS
Solve the following set of equations 6x-4y+8z=112 -5x-3y+7z=75 14x+9y-5z=-67
Answer: x=2, y=-5, z=10
EXERCISE
3x+y+z+w=24
x-3y+7z+w=12
2x+2y-3z+4w=17
x+y+z+w=0
You can perform operations in MATLAB in two ways:
1. In the interactive mode, in which all commands are entered directly in the
Command window, or2. By running a MATLAB program stored in
script file.
This type of file contains MATLAB commands, so running it is equivalent to typing all the commands—one at a time—at the Command window prompt.
You can run the file by typing its name at the Command window prompt.
1-27
COMMENTS
The comment symbol may be put anywhere in the line. MATLAB ignores everything to the right of the % symbol. For example,
>>% This is a comment.>>x = 2+3 % So is this.x = 5
Note that the portion of the line before the % sign is executed to compute x.
1-28
HOW TO CREATE M-FILE
Select NEW from the FILE menu. Then select BLANK M-file
In the new M-file, save the M-file to example1.
In the example1, please write down the following:
The MATLAB Command window with the Editor/Debugger open
1-29
RUN SCRIPT M-FILE
Two method to run script M-file
Or
From command window, by typing
run myscript
Red letter refer to user defined name for M-file.
KEEP IN MIND WHEN USING SCRIPT FILES:
1. The name of a script file must begin with a letter, and may include digits and the underscore character, up to 31 characters.
2. Do not give a script file the same name as a variable.
3. Do not give a script file the same name as a MATLAB command or function. You can check to see if a command, function or file name already exists by using the exist command.
1-30
Input/output commands
1-35
Command Descriptiondisp(A) Displays the contents, but
not the name, of the array A.
disp(’text’) Displays the text string enclosed within quotes.x = input(’text’) Displays the text in quotes, waits for user input from the keyboard,
and stores the value in x.x = input(’text’,’s’) Displays the text in quotes, waits for user input from the keyboard,
and stores the input as a string in x.
Example of a Script File
Problem:
The speed v of a falling object dropped with no initial velocity is given as a function of time t by v = gt.
Plot v as a function of t for 0 ≤ t ≤ tf, where tf is the final time entered by the user.
1-36
Example of a Script File (continued)
% Program falling_speed.m:% Plots speed of a falling object.% Created on March 1, 2004 by W. Palm%% Input Variable:% tf = final time (in seconds)%% Output Variables:% t = array of times at which speed is % computed (in seconds)% v = array of speeds (meters/second)%
1-37
Example of a Script File (continued)
% Parameter Value:g = 9.81; % Acceleration in SI units%% Input section:tf = input(’Enter final time in seconds:’);%
1-38
Example of a Script File (continued)
% Calculation section:dt = tf/500;% Create an array of 501 time values.t = [0:dt:tf];% Compute speed values.v = g*t;%% Output section:Plot(t,v),xlabel(’t (s)’),ylabel(’v m/s)’)
1-39
EXAMPLE In the absence of drag, the propulsion power requirements for a spacecraft are determined fairly simply. Recall from basic physical science that
F = ma
In other words, force (F) is equal to mass (m) times acceleration (a). Work (W) is force times distance (d), and since power (P) is work per unit time, power becomes force times velocity (v):
The Voyager 1 and 2 spacecraft explored the outer solar system during the last quarter of the 20th century. The power generators (low-level nuclear reactors) on each spacecraft are expected to function until at least 2020. The power source is a sample of plutonium-238, which, as it decays, generates heat that is used to produce electricity. At the launch of each spacecraft, its generator produced about 470 watts of power. Because the plutonium is decaying, the power production had decreased to about 335 watts in 1997, almost 20 years after launch. This power is used to operate the science package, but if it were diverted to propulsion, how much acceleration would it produce in the spacecraft? Voyager 1 is currently traveling at a velocity of 3.50 AU/year (an AU is an astronomical unit), and Voyager 2 is traveling at 3.15 AU/year. Each spacecraft weighs 721.9kg.
Change velocity AU to m/s
clear, clc
%Example 2.4
%Find the possible acceleration of the Voyager 1
%and Voyager 2 Spacecraft using the on board power
%generator
format short
mass=721.9; %mass in kg
power=335; %power in watts
velocity=[3.5 3.15]; %velocity in AU/year
%Change the velocity to m/sec
velocity=velocity*150e9/365/24/3600
%Calculate the acceleration
acceleration=power./(mass.*velocity)