Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB for Engineers Chapter 1 An Overview Of MATLAB.

Similar presentations


Presentation on theme: "MATLAB for Engineers Chapter 1 An Overview Of MATLAB."— Presentation transcript:

1 MATLAB for Engineers Chapter 1 An Overview Of MATLAB

2 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.

3 Assessment Test (s) 20 Assignment(s) /Quiz (s) 30 Final Exam 50

4 Reference 1. Palm, W.J., Introduction to Matlab 7 for Engineers, McGraw-Hill, New York. 2. Hanselman et al., Mastering MATLAB 7, Pearson Education Inc, New Jersey. 3. Amos, G., MATLAB: An Introduction with Application, 2nd Ed, John Wiley Inc, USA. 4. Moore, H., MATLAB for Engineers, 2nd Ed., Prentice Hall, New Jersey.

5 MATLAB windows The default view when opening MATLAB includes
1) current folder window 2) command window 3) workspace window 4) command history window

6

7 description Current folder window list all the files in the active directory. Command window use to write and execute MATLAB code Workspace window keeps track of the variables you have defined as you execute them in command window Command history records the command you issued in command window

8 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) -1

9 Command history window
Allow 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

10 Workspace window Keeps track of the variables user have defined when execute command in command window Now user probably has only one variables which is ans with value of 25 To add variables, type A=5 in command window Observe the changes to workspace window For now, user can enter a simple one-dimensional matrix by typing >> b=[1,2,3,4] b = Notice that variable b has been added to the workspace with array of 1x4

11 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

12 Workspace window Now user defined a two-dimensional matrix as follow
Notice that c appears in the workspace window as a 3x4 matrix

13 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

14 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 1-5

15 An Example Session >> 8/10 ans = 0.8000 >> 5*ans 4
>> r=8/10 r = >> r >> s=20*r s = 16 1-4

16 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

17 First Parentheses, evaluated starting with the innermost pair.
Order of Operations 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. 1-6

18 Examples of Precedence >> 8 + 3*5 ans = 23 >> 8 + (3*5)
>>(8 + 3)*5 55 >>4^2­12­ 8/4*2 >>4^2­12­ 8/(4*2) 3 1-7 (continued …)

19 Examples of Precedence (continued)
>> 3*4^2 + 5 ans = 53 >>(3*4)^2 + 5 149 >>27^(1/3) + 32^(0.2) 5 >>27^(1/3) + 32^0.2 >>27^1/3 + 32^0.2 11 1-8

20 example Height of a cylinder is 10cm with radius of 5cm. Find the surface area.

21 The Assignment Operator =
Typing x = 3 assigns the value 3 to the variable x. We can then type x = x This assigns the value = 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

22 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 where P = pressure in kPa, V = volume in m3, N = number of kmoles of gas in the sample, R = ideal gas constant, kPa m3/kmol K, and T = 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 and MW = 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.

23

24 Commands for managing the work session
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. 1-10

25 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

26 Special Variables and Constants
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. 1-12

27 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)

28 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.5i and x = 7/(2i) = –3.5i. 1-13

29 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= i

30 Numeric Display Formats
Command Description and Example format short Four decimal digits (the default); format long 16 digits; format short e Five digits (four decimals) plus exponent; e+03. format long e 16 digits (15 decimals) plus exponent; e–04. 1-14

31 • To compute w = 5 sin u for u = 0, 0.1, 0.2, …, 10, the session is;
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 formula w = 5 sin u 101 times. 1-15

32 To find specific value in array >>u(7) ans = 0.6000 >>w(7)
Array Index To find specific value in array >>u(7) ans = 0.6000 >>w(7) 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

33 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.

34 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 .*)

35 exercise

36 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 >> a=[cos(0):0.02:log10(100)]; >> a(25) ans = 1.4800

37 transposition Transpose operator changes rows to column and vice versa. Degrees=[ ] Degrees’ To create tables Radian=[ ] Table=[Degrees’,Radians’]

38 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 = N

39

40 To find the roots of x3 – 7x2 + 40x – 34 = 0, the session is
Polynomial Roots To find the roots of x3 – 7x2 + 40x – 34 = 0, the session is >>a = [1,-7,40,-34]; >>roots(a) ans = i i 1.0000 The roots are x = 1 and x = 3 ± 5i. 1-17

41 Polynomial exercise Use MATLAB to find the roots of the polynomial x+6x2+x3. Answer: x=-10 and 2 ± 5i

42 Some Commonly Used Mathematical Functions
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. 1-18

43 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

44 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 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. 1-24

45 A graphics window showing a plot.
X=[0: 0.02: 8] Y=5*sin(x) Plot (x,y) and label x and y-axis 1-23

46 Test you understanding by

47 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')

48 Solution of Linear Algebraic Equations 6x + 12y + 4z = 70
>>Solution = A\B Solution = 3 5 -2 The solution is x = 3, y = 5, and z = –2. 1-26

49 Try this Solve the following set of equations Answer: x=2, y=-5, z=10

50 exercise 3x+y+z+w=24 x-3y+7z+w=12 2x+2y-3z+4w=17 x+y+z+w=0

51 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, or 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

52 >>% This is a comment. >>x = 2+3 % So is this. x = 5
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

53 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:

54 The MATLAB Command window with the Editor/Debugger open
1-29

55 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.

56 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

57 Input/output commands
Command Description disp(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. 1-35

58 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

59 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

60 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

61 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

62 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):

63 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 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 kg Change velocity AU to m/s

64 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=[ ]; %velocity in AU/year %Change the velocity to m/sec velocity=velocity*150e9/365/24/3600 %Calculate the acceleration acceleration=power./(mass.*velocity)

65


Download ppt "MATLAB for Engineers Chapter 1 An Overview Of MATLAB."

Similar presentations


Ads by Google