matlab & its applications in engineering 李清都 副教授 [email protected]

Download MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

If you can't read please download the document

Upload: monserrat-ashburn

Post on 15-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

  • Slide 1

MATLAB & Its Applications In Engineering [email protected] Slide 2 Lect. 1: Introduction Contents Covered: Why MATLAB? Simple demos. How to learn MATLAB? Objectives: Establish the basic concepts of MATLAB Understand the advantage and disadvantage of MATLAB Slide 3 Why MATLAB There are totally 87 students I may arrange 10 times of assignments Each time I will randomly look through 20 students work Question: What is the probability that you will never be selected? How high is the risk not to do the assignments? Slide 4 Why MATLAB 1-[(87-20)/87] 10 = ? Want to know the result ?! Calculate by hand use a calculator use C language I have much more important things to do than to calculate this boring figure Slide 5 Why MATLAB Using C language: main() { float m; m = 1-((107-20)/107)^10; printf( %f ,m); } Slide 6 Why MATLAB Using C language: main() { float m; m = 1-((107-20)/107)^10; printf( %f ,m); } If only there was just line 3 Slide 7 You need such a powerful tool Powerful compute ability Easy of use MATL AB Slide 8 MATLAB the most popular computer program optimized to perform engineering and scientific calculations. Slide 9 What can MATLAB do? Mathematical computing Visual results System modeling Graphic user interface Slide 10 The advantages of MATLAB Easy of use Platform independence Predefined functions Device-Independent Plotting Graphic user interface MATLAB compiler Slide 11 The disadvantages of MATLAB Slower execute speed Matlab is interpreted language other than compiled language All the variables use the highest precision Higher cost Slide 12 The MATLAB Environment Command window Work Space Command history Slide 13 How to learn MATLAB? The most important is to program more and practice more The best teacher is Matlab help, not me, nor any person else Think more your idea search in help find a function programming Good programming practice Slide 14 Assignment: Install Matlab and run the demo Any question or suggestion, please email to: [email protected] with title: matlab - your name - your question Slide 15 MATLAB & Its Applications In Engineering [email protected] Slide 16 Lect. 2: Variables & Arrays Contents Covered: basic conceptions of MATLAB variables and arrays initialize/save/load MATLAB variables and arrays Objectives: Firmly grasp the naming rules of MATLAB variables. Fully grasp the initialize and addressing method of a array. Memorize the basic special variables, such as pi, i, j, ans, NaN. Grasp how to save and load MATLAB variables Slide 17 Arrays Vectors: 1 dimension Matrix: 2 or more dimensions A scalar is an array with only one row and one column. All data, even scalars, are arrays. Slide 18 Variables Naming Rule must begin with a letter, followed by any combinations of letters, numbers, and the underscore character. C can begin with _ !!! Only the first 31 characters are significant. A MATLAB variable is a region of memory containing an array, which is known by a user-specified name. Slide 19 Special Variables i, j, pi, NaN, ans, eps MATLAB has some predefined variables and users should avoid using them create new variables. Slide 20 Good Programming Practice Must using meaningful names Include a data dictionary in the header of the program Use lowercase letters to name a variable Use underscore as separator if the name is long Slide 21 Initialize the Array There are 3 common ways: Using assignment statement Read from a file From keyboard Slide 22 Initializing Variables in Assignment Statement Using assignment statement Var = expression Initializing with shortcut expression Var = first : incr : last Initializing with build-in functions Var = zeros(?) Var = ones(?) Slide 23 Initializing Variables from file MATLAB formatted file load xxx.mat save file_name var1, var2, var3 ASCII file load file_name.xxx -ascii Slide 24 Initializing Variables with Keyboard Input var = input(Enter an input value:) Slide 25 Multi-dimensional Arrays Create a multi-dimensional array e.g. c is a 2x3x2 array c(:, :, 1) = [1 2 3; 4 5 6]; c(:, :, 2) = [7 8 9; 0 1 2]; MATLAB always allocates array elements in column major order. a(1, 1, 1) -> a(2, 1, 1) -> a(1, 2, 1) -> a(2, 2, 1) -> a(1, 3, 1) a(10) = 1 Slide 26 Subarray Select and use subsets of a array c = [1 2 3; 4 5 6]; a = c(1, [ 2 3]) b = c([1 2], [ 2 3]) The end function c(1, 2:end) Assignment to subarray c(1, [ 2 3]) = [12 13] Assigning a scalar to a subarray c(2, [ 2 3]) = 99 Slide 27 Assignment: Excises 2.1, 2.2, 2.3 2.4 Slide 28 MATLAB & Its Applications In Engineering [email protected] Slide 29 Lect. 3: Operations Contents Covered: basic conceptions of scalar/array/matrix operations the main differences between array & matrix operation operation rules Objectives: Firmly grasp the differences between array and matrix operation. Fully grasp the hierarchy & the rules of the operations Memorize some basic MATLAB functions, such as sqrt, Start to write M-file and debug it Slide 30 MATLAB Operations Scalar operation Array operation Matrix operation the differences between array operation & matrix operation!!! Slide 31 Scalar operation Examples: A = 4*2 A = 2^((8+2)/5) A = [ 1 2 3 4]; b = A^2; Slide 32 Array operation Examples: A = [ 1 2 3 4]; B = [ 5 6 7 8]; C = A.* B; If as array operation, the result is [ 5 12 21 32] Array operations are operations performed between arrays on an element-by-element basis. Slide 33 Matrix operation Examples: A = [ 1 2 3 4]; B = [ 5 6 7 8]; C = A * B; If as matrix operation, the result is [ 19 22 43 50] Matrix operations follow the normal rules of linear algebra such as matrix. Slide 34 Array & Matrix operators OperationArray operatorMatrix operator Addition++ Sub.-- Multiplex..** Right Div..// Left Div..\\ Exponentiation.^^ Usually array operators have one extra . than matrix operators. Slide 35 Hierarchy of Operations Rules: 1.The contents of all parentheses 2.Exponentials 3.Multiplication and division 4.Additions and subtractions Question: What is the execute sequences of the following assignment? a = sin(pi^2/2*3+1) + 4*(2-1) Slide 36 Build-in MATLAB functions min, max sqrt, mod sin, cos, tan, atan, asin, acos abs, angle exp, log ceil, round, floor, fix These are very common MATLAB functions which we will use quite frequently. Slide 37 M-File File new M-file And then write your code Debug Think Slide 38 Assignment: Excises 2.6, 2.7, 2.8, 2.9 Slide 39 MATLAB & Its Applications In Engineering Slide 40 Lect. 4: Display & Plotting Contents Covered: MATLAB data format three functions: disp, fprintf, plot the elements of a MATLAB figure Objectives: Understand the concepts of MATLAB data format Firmly grasp the usage of disp, fprintf, plot Strengthen the skill on writing and debugging M-file Slide 41 Data Formats format Set display format for output Syntax 1.format format by itself, changes the output format to the default appropriate for the class of the variable currently being used. For floating-point variables, for example, the default is format short (i.e., 5-digit scaled, fixed-point values). Slide 42 Data Formats 2.format type format type changes the format to the specified type. The tables shown below list the allowable values for type. 3. format('type') format('type') is the function form of the syntax. Slide 43 Data Formats Short Long Short e Short g Long e Long g Bank Hex Rat Compact Loose + format options format command only controls the display format. It will not change the precision of the data. Slide 44 Data Formats TypeResult shortScaled fixed point format, with 4 digits after the decimal point. For example, 3.1416. longScaled fixed point format with 14 or 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.141592653589793. long eFloating point format, with 14 or 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.141592653589793e+000. short gBest of fixed or floating point, with 4 digits after the decimal point. For example, 3.1416. long gBest of fixed or floating point, with 14 to 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.14159265358979. Slide 45 Data Formats Value for typeResult +The symbols +, - and blank are printed for positive, negative and zero elements. Imaginary parts are ignored bankFixed dollars and cents. For example, 3.14 hexHexadecimal (hexadecimal representation of a binary double- precision number). For example, 400921fb54442d18 ratRatio of small integers. For example, 355/113 Slide 46 Data Formats Value for typeResult Example compact Suppresses excess line feeds to show more output in a single screen. Contrast with loose. theta = pi/2 theta = 1.5708 looseAdds linefeeds to make output more readable. Contrast with compact. theta = pi/2 theta = 1.5708 Slide 47 Data Formats Examples 1.>> format long >> pi ans =3.141592653589793 2. format + >> -2 ans = - Slide 48 Data Formats Note The format function affects only how numbers are displayed, not how MATLAB computes or saves them. Slide 49 disp disp( x) disp(X) displays an array, without printing the array name. If X contains a text string, the string is displayed. Another way to display an array on the screen is to type its name, but this prints a leading "X=," which is not always desirable. Slide 50 disp Note that disp does not display empty arrays. Examples 1.str = [ the value of pi = num2str(pi) ] disp(str) The result: the value of pi = 3.1416 Slide 51 disp 2. >> x = [1 2 3]; >> disp(['The values of x are: ', num2str(x)]); The values of x are: 1 2 3 (The num2str function converts numbers to their string representations. This function is useful for labeling and titling plots with numeric values.) Slide 52 fprintf fprintf( format, data) fprintf( format, data) formats data and displays the results on the screen. Examples 1. This command fprintf('Hello'); The result: >>Hello Slide 53 fprintf 2.fprintf(the value of pi is %f \n, pi); The result: >> fprintf('the value of pi is %f',pi) >>the value of pi is 3.141593 Slide 54 Programming pitfalls Note fprintf will only display the real part of a complex number!!! example: a = 3+4i; fprintf(fprintf: a = %f, a); Slide 55 Summary There are 3 ways to display a data: 1)Leave the semicolon off the end of the statement 2)Use disp function 3)Use fprintf function It is better to use disp to display a complex number. Slide 56 Plotting It is really not so difficult as you imaged. How great if I can create a beautiful graph with MATLAB! Slide 57 Whats the first ? Right! You need a piece of paper. figure(number) Slide 58 plot Plot(x,y,s) x axis and y axis linetype y . - m o : c x x- -. r + -- Slide 59 plot title figure name xlabel/ylabel axis legend graphic symbol grid on off grid Slide 60 Then you can plot! x = 1:100; y = sin(x*pi/10); plot(x,y) Slide 61 Then you can plot! x = 1:100; y = sin(x*pi/10); plot(x,y,--r,linewidth,5) Slide 62 Plot more x = 1:100 y = sin(x*pi/10) z = 0.5*cos(x*pi/20) plot(x,y,x,z) Slide 63 Add more control title('my first plot') xlabel('x') ylabel('y') grid on axis([0 110 -2 2]) legend('sin(x*pi/10)', '0.5*cos(x*pi/20)'); Slide 64 plot3 3-D line plot Syntax plot3(X1,Y1,Z1,...) plot3(X1,Y1,Z1,LineSpec,...) plot3(...,'PropertyName',PropertyValue,...) h = plot3(...) Slide 65 plot3 Examples Plot a three-dimensional helix. t = 0:pi/50:10*pi; plot3(sin(t),cos(t),t) grid on axis square Slide 66 plot3 Slide 67 subplot Create axes in tiled positions Examples To plot income in the top half of a figure and outgo in the bottom half, Slide 68 subplot income = [3.2 4.1 5.0 5.6]; outgo = [2.5 4.0 3.35 4.9]; subplot(2,1,1); plot(income) title('Income') subplot(2,1,2); plot(outgo) title('Outgo') Slide 69 subplot Slide 70 Logarithmic scales Purpose Semilog scale plot of frd object Syntax semilogx(...) same as plot semilogy(...) same as plot Slide 71 Logarithmic scales Description semilogx(...) is the same as plot(...), except a logarithmic (base 10) scale is used for the x-axis. semilogy(...) is the same as plot(...), except a logarithmic (base 10) scale is used for the y-axis. Slide 72 Logarithmic scales x = 1:100 y = x.^3 semilogy(x,y) Slide 73 Logarithmic scales semilogx(x,y) Slide 74 Logarithmic scales loglog(x,y) Slide 75 MATLAB & Its Applications In Engineering [email protected] Slide 76 Lect. 5: Branch Statement Contents Covered: Top-down design Techniques relational & logical operators Branch statements: if-elseif-else-end, switch-case-otherwise-end Objectives: Understand the concepts of Top-down design flow firmly grasp the usage of relational & logical operators Firmly grasp the usage of if-elseif-else-end, switch case otherwise end Strengthen the skill on writing and debugging M-file Slide 77 Top-down Design Flow Slide 78 More complicated control statements To solve complicated problems, you have to write more complicated programs. branching & looping Slide 79 Relational operators == ~= > < >= Example using if construct score = input(please input your score: ); if score >= 90 grade = Excellent; elseif score >= 70 grade = Good; elseif score >= 60; grade = Passed; else grade = Failed; end disp(grade); Slide 87 The switch construct switch ( swtich_expression) case case_expr_1 statement_1 case case_expr_2 statement_2 otherwise statement_3 end Slide 88 Example using switch construct password = input(please input your password: ); switch password case matlab privilege = WRITE_ONLY; case pld privilege = READ_ONLY; otherwise privilege = FORBIDDEN; end Slide 89 Assignment: Excises 3.2, 3.3, 3.4, 3.5 Slide 90 MATLAB & Its Applications In Engineering [email protected] Slide 91 Lect. 5: Branch Statement Contents Covered: Top-down design Techniques relational & logical operators Branch statements: if-elseif-else-end, switch-case-otherwise-end Objectives: Understand the concepts of Top-down design flow firmly grasp the usage of relational & logical operators Firmly grasp the usage of if-elseif-else-end, switch case otherwise end Strengthen the skill on writing and debugging M-file Slide 92 Top-down Design Flow Slide 93 More complicated control statements To solve complicated problems, you have to write more complicated programs. branching & looping Slide 94 Arithmetic operators + - * / Slide 95 Relational operators == ~= > < >= Good Programming practice Always use parentheses to indicate the order 7+3 < 2+11 >> 7+3 Good Programming practice (7+3) < (2+11) >> (7+3)1&2 2>1&2 >> 0>1&2 >> 2>1&2 ans =0 ans =1 Slide 100 Good Programming practice 2+7>12> 2+7>122+7>12 >> 2&1>2+7>12 ans =0 Slide 101 What is the result? a = 0; b = sin(pi); c = (a == b); Slide 102 Logical functions isequal( ) isempty ( ) isinf ( ) isnan ( ) isnumeric ( ) Slide 103 Logical functions isequal( ) Examples Slide 104 Logical functions isempty ( ) Examples Slide 105 Logical functions isinf ( ) Examples Slide 106 Logical functions isnan ( ) Examples Slide 107 Logical functions isnumeric ( ) Examples Slide 108 The if construct if expression_1 statement_1 elseif expression_2 statement_2 else statement_3 end Slide 109 Example using if construct score = input(please input your score: ); if score >= 90 grade = Excellent; elseif score >= 70 grade = Good; elseif score >= 60; grade = Passed; else grade = Failed; end disp(grade); Slide 110 The switch construct switch ( swtich_expression) case case_expr_1 statement_1 case case_expr_2 statement_2 otherwise statement_3 end Slide 111 Example using switch construct Slide 112 Assignment: Excises 3.2, 3.3, 3.4, 3.5 Slide 113 MATLAB & Its Applications In Engineering [email protected] Slide 114 Lect. 6: Loops Contents Covered: Loop statements: while-end, for-end Objectives: Understand the concepts of loops Firmly grasp the usage of while-end, for-end Strengthen the skill on writing and debugging M-file Slide 115 Loops Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. Slide 116 The while construct while Repeatedly execute statements while condition is true Slide 117 The while construct Syntax while expression code_block end Slide 118 Example using while construct Example ATTENTION Slide 119 Example using while construct The result Slide 120 Example using while construct Calculate the average (arithmetic mean) and the standard deviation of a set of input positive numbers. Slide 121 How to program? 1.State the problem 2.Define the inputs/outputs 3.Design the algorithm think more!!! Slide 122 The algorithm 1.input the numbers 2.Calculate the value until a negative number is input a) a variable sum_x is needed to store the summary of the inputs b) a variable sum_x2 is needed to store the summary of the square value of the inputs 3. Print the results Slide 123 The for construct For Execute block of code specified number of times Slide 124 The for construct Syntax for index = expr code_block end Slide 125 Example using for construct Example Slide 126 Example using for construct Example Slide 127 Difference between while and for Slide 128 Break & Continue Break Terminate execution of for or while loop Continue Pass control to next iteration of for or while loop Slide 129 Break & Continue s1 = 0; for ii=1:10 if (ii >5) & (ii Break & Continue s2 = 0; for ii=1:10 if (ii >5) & (ii