资源描述:
1 沈志忠 機械與機電工程學系 Programming in MatlabProgramming in Matlab Chapter 2 –MATLAB BASICS 2 Programming in MatlabProgramming in Matlab 2.1 Variables and Arrays 2 3 Programming in MatlabProgramming in Matlab MATLAB Variables The fundamental unt of data in any MATLAB program is the array. Arrays – generic terms for a collection of data values orginized into one or more dimensions Vectors – one dimensional arrays Matrices – two or more dimensional arrays A MATLAB variable with a user-specified name is a region of memory containing an array. MATLAB variable names must begin with a letter, followed by any conbination of letters, numbers, and the underscore _ character. 4 Programming in MatlabProgramming in Matlab MATLAB Variables Make sure that your variable names are unique in the first 63 31 for Version 6.5 characters. Make sure that your variable names are unique in the first 63 31 for Version 6.5 characters. Always give your variables descriptive and easy-to- remember names. - currency exchange rate exchange_rate Create a data dictionary for each program to make program maintenance easier. - A data dictionary lists the definition of each variable used in a program. - invaluable when you or another person have to go back and modify the program at a later time. Be sure to capitalize a variable exactly the same way each time that it is used. Use all lowercase letters for ordinary variable names if not required. Always give your variables descriptive and easy-to- remember names. - currency exchange rate exchange_rate Create a data dictionary for each program to make program maintenance easier. - A data dictionary lists the definition of each variable used in a program. - invaluable when you or another person have to go back and modify the program at a later time. Be sure to capitalize a variable exactly the same way each time that it is used. Use all lowercase letters for ordinary variable names if not required. 3 5 Programming in MatlabProgramming in Matlab MATLAB Variables The most common types of MATLAB variables double 64-bit double-precision floating-point numbers - 10-308 10308with 15 to 16 significant decimal digits of accuracy char 16-bit values representing a single character sef 1 212 1364 6 Programming in MatlabProgramming in Matlab MATLAB Variables date ‘Sep. 24, 2003.’ 114 character array Strongly-typed language C, PASCAL Weakly-typed language MATLAB 4 7 Programming in MatlabProgramming in Matlab 2.2 Initializing Variables in MATLAB Three common ways to initialize a variable in MATLAB 1. Assign data to the variable in an assignment statement. 2. data into the variable from the keyboard. 3. Read data from a file. 8 Programming in MatlabProgramming in Matlab The general var expression var name of a variable expression a scalar constant, an array, other variables, and mathematical operations p. 2526 Using Assignment Statements 5 9 Programming in MatlabProgramming in Matlab Using Assignment Statements The number of elements in every row column of an array must be the same. The number of elements in every row column of an array must be the same. Use a semicolon at the end of all MATLAB assignments to suppress echoing in the Command Window. improve cution speed Remove the semicolon from the statement for program debugging. Use a semicolon at the end of all MATLAB assignments to suppress echoing in the Command Window. improve cution speed Remove the semicolon from the statement for program debugging. 10 Programming in MatlabProgramming in Matlab General notation for colon operator firstincrlast v 15 w 125 x 1210 x 1 3 5 7 9 angles 0.010.011.00 * pi; Transpose operator ’ f [14]’; g 14; h [g’ g’]; Using Shortcut Expressions 6 11 Programming in MatlabProgramming in Matlab Using Built-In Functions 12 Programming in MatlabProgramming in Matlab in1 ‘Enter data ‘; Enter data 1.23 in2 ‘Enter data ‘, ‘s’; Enter data 1.23 Store the character string ‘1.23’ into in2 Using Keyboard 7 13 Programming in MatlabProgramming in Matlab 2.3 Multidimensional Arrays 14 Programming in MatlabProgramming in Matlab Accessing Multidimensional Arrays with One Dimension Always use proper number of dimensions when addressing a multidimensional array. Always use proper number of dimensions when addressing a multidimensional array. a [1 2 3; 4 5 6; 7 8 9; 10 11 12] a 1 2 3 4 5 6 7 8 9 10 11 12 a5 ans 2 a5 a1,2 Don’t use this feature under normal circumstance. 8 15 Programming in MatlabProgramming in Matlab 2.4 Subarrays arr1 [1.1 -2.2 3.3 -4.4 5.5]; arr13 arr13 3.3 arr1[1 4] arr1[1 4] 1.1 -4.4 arr1125 arr1125 1.1 3.3 5.5 16 Programming in MatlabProgramming in Matlab Subarrays arr2 [1 2 3; -2 -3 -4; 3 4 5]; arr21, ans 1 2 3 arr2,123 same as arr2,[1 3] ans 1 3 -2 -4 3 5 −−− 543 432 321 2arr −−− 543 432 321 2arr 9 17 Programming in MatlabProgramming in Matlab The end Function When used in an array subscript, end returns the highest value of the subscript. arr3 [1 2 3 4 5 6 7 8]; arr35end ans 5 6 7 8 arr3end ans 8 arr42end,2end ans 6 7 8 10 11 12 1211109 8765 4321 4arr 18 Programming in MatlabProgramming in Matlab Subarrays on the Left-Hand Side of an Assignment Statement Assign values to a subarray arr412,[1 4] [20 21; 22 23] arr4 20 2 321 22 6 723 9 10 11 12 Assign values to an array arr4 [20 21; 22 23] arr4 20 21 22 23 1211109 8765 4321 4arr 10 19 Programming in MatlabProgramming in Matlab Assigning a Scalar to a Subarrays arr412,12 1 arr4 1 1 3 4 1 1 7 8 9 10 11 12 Expand an existing array arr5 [arr4 [1 1 1]’] arr5 1 1 3 4 1 1 1 7 8 1 9 10 11 12 1 arr6 [arr4; 1 1 1 1] arr6 1 1 3 4 1 1 7 8 9 10 11 12 1 1 1 1 1211109 8765 4321 4arr 20 Programming in MatlabProgramming in Matlab Subarrays For assignment statements involving subarrays, the shapes of the subarrays on both sides of the equal sign must match. For assignment statements involving subarrays, the shapes of the subarrays on both sides of the equal sign must match. Be sure to distinguish between assigning values to a subarray and assigning values to an array. MATLAB behaves differently in these two cases. Be sure to distinguish between assigning values to a subarray and assigning values to an array. MATLAB behaves differently in these two cases. 11 21 Programming in MatlabProgramming in Matlab 2.5 Special Values Never redefine the meaning of a predefined variable in MATLAB. It is a recipe for disaster, producing subtle and hard-to-find bugs. Never redefine the meaning of a predefined variable in MATLAB. It is a recipe for disaster, producing subtle and hard-to-find bugs. 22 Programming in MatlabProgramming in Matlab 2.6 Display Output Data Default at for numbers in MATLAB 4 digits after the decimal point. x 100.11 x 100.1100 y 1001.1 y 1.0011e003 z 0.00010011 z 1.0011e-004 12 23 Programming in MatlabProgramming in Matlab Display Output Data 24 Programming in MatlabProgramming in Matlab The disp function disppi 3.1416 str [‘The value of pi ‘ num2strpi]; dispstr The value of pi 3.1416 str [‘The value of pi ‘ pi] str The value of pi 13 25 Programming in MatlabProgramming in Matlab atted Output fprintf function General fprintf at, data at a string describing the way the data to be printed data scalars to be printed 26 Programming in MatlabProgramming in Matlab atted Output fprintf function fprintfThe value of pi is f \n, pi The value of pi is 3.141593 fprintfThe value of pi is 6.2f \n, pi The value of pi is 3.14 x 2*1-2*i3; dispx -22.0000 4.0000i fprintf x 8.4f\n, x x -22.0000 The fprintf function only displays the real part of a complex number. The fprintf function only displays the real part of a complex number. 14 27 Programming in MatlabProgramming in Matlab 2.7 Data Files To load and save data files in MATLAB help save save filename saves all workspace variables to the binary “MAT-file“ named filename.mat. If filename has no extension, .mat is assumed. save filename x y z saves x, y, and z. The wildcard * is to save only those variables matching a pattern. save x.dat x -ascii save x in a file named x.dat using 8-digit ASCII . 28 Programming in MatlabProgramming in Matlab Data Files load filename To retrieve all variables from a file named filename.mat and treats it as a binary “MAT-file“. If filename has an extension other than .mat, it is treated as ASCII. load filename x y z ... loads just the specified variables. The wildcard * loads variables matching a pattern MAT-file only. If data must be exchanged between MATLAB and other programs, save the MATLAB data in ASCII at. If only used in MATLAB, save the data in MAT-file at. If data must be exchanged between MATLAB and other programs, save the MATLAB data in ASCII at. If only used in MATLAB, save the data in MAT-file at. Save ASCII data files with a “dat” file extent to distinguish them from MAT-files. Save ASCII data files with a “dat” file extent to distinguish them from MAT-files. 15 29 Programming in MatlabProgramming in Matlab Data Files x [ 1.23 3.14 6.28 -5.1 7.00 0 ]; save x.dat x -ascii dir C\MATLAB6p5\work 的目錄 2004/10/25 下午 0659 98 x.dat type x.dat 1.2300000e000 3.1400000e000 6.2800000e000 -5.1000000e000 7.0000000e000 0.0000000e000 30 Programming in MatlabProgramming in Matlab 2.8 Scalar and Array Operations General variable_name expression; Note that the equal sign called assignment operator means store the value of expression into location variable_name. 16 31 Programming in MatlabProgramming in Matlab Scalar Operations When parentheses are used, the expressions inside the parentheses are uated first. 2 82/5 2 10/5 2 2 4 32 Programming in MatlabProgramming in Matlab Matrix Operations Be careful to distinguish between array operations and matrix operations in your MATLAB code. Be careful to distinguish between array operations and matrix operations in your MATLAB code. Array operations element-by-element basis The number of rows and column in both arrays must be the same p.46. Matrix operations rules of linear algebra For matrix multiplication a*b, the number of columns in matrix a must be equal to the number of rows in b. ∑ n k jkbkiajic 1 ,,, MATLAB uses a period e.g. a.*b before the operation symbol to indicate an array operation. 17 33 Programming in MatlabProgramming in Matlab 34 Programming in MatlabProgramming in Matlab 2.9 Hierarchy of Operations Use parentheses as necessary to make your equations clear and easy to understand. Use parentheses as necessary to make your equations clear and easy to understand. 18 35 Programming in MatlabProgramming in Matlab 2.10 Built- in MATLAB Functions 36 Programming in MatlabProgramming in Matlab 2.11 Introduction to Plotting x 0110; y x.2-10.*x15; plotx,y; titlePolt of y x.2-10.*x15; xlabelx; ylabely; grid on; Printing a plot Select the “File/Export” menu option in the Figure Window. print –dtiff my_image.tif 19 37 Programming in MatlabProgramming in Matlab Multiple Plots x 0pi/1002*pi; y1 sin2*x; y2 2*cos2*x; plotx,y1,x,y2; 38 Programming in MatlabProgramming in Matlab Plot Attributes 20 39 Programming in MatlabProgramming in Matlab Legends legend ‘string1’, ‘string2’, , pos string1, string2 labels associated with the lines plotted pos an integer specifying where to place the legend Ver. 6.5 40 Programming in MatlabProgramming in Matlab x 0pi/1002*pi; y1 sin2*x; y2 2*cos2*x; plotx,y1,x,y2; title‘Plot of fx sin2x and its derivative’; xlable‘x’; ylable‘y’; legendfx,d/dx fx’,1; Grid on; 21 41 Programming in MatlabProgramming in Matlab Combinations of Linear and Logarithmic x and y Scales 42 Programming in MatlabProgramming in Matlab 2.12 Examples Good Programming Practices data dictionary descriptive variable names Appropriate units attached to all printed values 1. Example 2.3 – Temperature Conversion 2. Example 2.4 – Maximum Power Transfer to a Load 3. Example 2.5 – Carbon 14 Dating Always include the appropriate units with any values that you read or write in a program. Always include the appropriate units with any values that you read or write in a program. 22 43 Programming in MatlabProgramming in Matlab Example 2.3 – Temperature Conversion 44 Programming in MatlabProgramming in Matlab Example 2.4 – Maximum Power Transfer to a Load LL LSTOT RIP RR V R V I 2 23 45 Programming in MatlabProgramming in Matlab 2.13 Debugging MATLAB Programs If you write a program of any size, it will not work the first time you try it Three types of errors in MATLAB programs 1. Syntax error - errors in the MATLAB statements, e.g. spelling errors or punctuation errors - Incorrect variable names MATLAB cannot detect this type of error. 2. Run-time error - illegal mathematical operations, e.g. 0/0 NaN, 1/0 Inf 3. Logical error - MATLAB cannot detect this type of error. - produces the wrong answer e.g. vel1, vel2. - checks the data or the logical structure of the program. 4. Typographical error may produce the above errors. 46 Programming in MatlabProgramming in Matlab Debugging Steps 1. Check the data to the program. Remove ‘;’ or add extra output statements 2. Check each of your assignment statements. Break a long statement into several smaller statements. Check the placement of parentheses in your assignment statements. Wrong order Make sure to initialize all of your variables. Be sure that any function are used in the correct units. 3. Add output statements at various points in your program. 4. Let somebody else look at your code. One is easily to overlook an error time after time. 24 47 Programming in MatlabProgramming in Matlab To reduce your debugging effort 1. Initialize all variables. 2. Use parentheses to make the functions of assignment statements clear. To reduce your debugging effort 1. Initialize all variables. 2. Use parentheses to make the functions of assignment statements clear.
展开阅读全文