Matlab应用技术._第1页
Matlab应用技术._第2页
Matlab应用技术._第3页
Matlab应用技术._第4页
Matlab应用技术._第5页
已阅读5页,还剩114页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Electrical Engineering Simulation and Computation 电气工程仿真与计算电气工程仿真与计算 电气工程与自动化学院电气工程与自动化学院 EESC 选用教材:选用教材: Matlab应用技术应用技术 在电气工程与自动化专业中的应用在电气工程与自动化专业中的应用 作者:王忠礼作者:王忠礼 段慧达段慧达 等等 出版社:清华大学出版社出版社:清华大学出版社 EESC Introduction to MATLAB ( (Matlab简介简介) ) Program Design ( (Matlab程序设计程序设计) ) Plotting(Matlab绘图)绘图)

2、 1 2 3 4 MatLAB Basic(Matlab基本知识)基本知识) Contents Introduction to MATLAB EESC nMatrix Laboratory nAdvantages of MATLAB nEase of use nPlatform independence nPredefined functions nPlotting nDisadvantages of MATLAB nCan be slow nExpensive Introduction to MATLAB EESC nMATLAB tool box(MATLAB工具箱)工具箱) nContr

3、ol Systems Toolbox(控制系统)(控制系统); nDatabase Toolbox(数据库)(数据库); nFilter Design Toolbox(滤波器设计)(滤波器设计); nFuzzy Logic Toolbox(模糊逻辑)(模糊逻辑); nNeural Network Toolbox(神经网络)(神经网络); nModel Predictive Control Toolbox(模型预测控制)(模型预测控制); nSignal Processing Toolbox(信号处理)(信号处理); nImage Processing Toolbox(图像处理)(图像处理);

4、Introduction to MATLAB EESC nMATLAB Desktop nCommand Window(命令窗口)(命令窗口) nCommand History Window(命令历史记录)(命令历史记录) nWorkspace Browser(工作空间)(工作空间) nCurrent Directory Browser(当前路径浏览)(当前路径浏览) nHelp Browser(帮助浏览)(帮助浏览) nEdit/Debug Window(编辑(编辑/调试窗口)调试窗口) nFigure Windows (图形窗口)(图形窗口) nLaunch Pad(登录)(登录) Int

5、roduction to MATLAB EESC Workspace Browser Command Window Current Directory Browser Command History Window To view or change the current directory Help Browser Introduction to MATLAB EESC nThe Command Window nThe command prompt() nEllipsis(),continuing on the next line Introduction to MATLAB EESC In

6、troduction to MATLAB nThe Command History Window EESC nThe Edit/Debug Window nCreate new M-files n“File/New/M-file” nClicking the Toolbar icon nOpen an existing one n“File/Open ” nClicking the Toolbar icon Introduction to MATLAB EESC Introduction to MATLAB EESC Introduction to MATLAB nFigure Window

7、EESC Introduction to MATLAB nThe MATLAB Workspace n whos n var1 n clear Deletes all variables nclear var1 var2 EESC Introduction to MATLAB EESC nGetting Help nUse the Help Browser nSelecting the Help icon nTyping helpdesk or helpwin in the Command window Introduction to MATLAB EESC nGetting Help nCo

8、mmand_line oriented way to get help nType help or help fun1 in the command window nSearches for an exact function name match nType lookfor command nSearches the quick summary information in each function for a match Introduction to MATLAB EESC nThe MATLAB Search Path nEnter a name at the MATLAB prom

9、pt nLook for the name as a variable nCheck to see if it is a built-in function or command nCheck to see if it is an M-file in the current directory nCheck to see if it is an M-file in any directory in the search path Introduction to MATLAB EESC nThe MATLAB Search Path nProgramming Pitfalls nNever us

10、e a variable with the same name as a MATLAB function or command nNever create an M-file with the same name as a MATLAB function or command nExamine and modify search path n“File/Set Path”, editpath, pathtool npath command Introduction to MATLAB MATLAB Basic EESC nVariable is a name given to a reserv

11、ed location in memory nclass_code = 111; nnumber_of_students = 65; nname = Sichuan Normal University; nradius = 5; narea = pi * radius2; Variables(变量)(变量) EESC nUse meaningful names for variables nMATLAB variable names nmust begin with a letter ncan contain any combination of letters, numbers and un

12、derscore (_) nMATLAB is case sensitive: “name”, “Name” and “NAME” are considered different variables nNever use a variable with the same name as a MATLAB command nNaming convention: use lowercase letters Variables EESC nThe fundamental unit of data is array scalar value vector matrix 15-2321 -41013

13、3 140-311 column row Array(数组)(数组) EESC nInitialization using assignment statements nx = 5 x = 5 ny = x + 1 y = 6 nvector = 1 2 3 4 vector = 1 2 3 4 Initializing Variables(变量初始化)(变量初始化) EESC nmatrix = 1 2 3; 4 5 6 nmatrix = 1 2 3 4 5 6 nmatrix = 1 2 3; 4 5 ? Error Initializing Variables EESC nInitia

14、lization using shortcut statements ncolon operator start:increment:end nx = 1:2:10 x = 1 3 5 7 9 ny = 0:0.1:0.5 y = 0 0.1 0.2 0.3 0.4 0.5 Initializing Variables EESC ntranspose operator(转置操作符)(转置操作符) nu = 1:3 u = 1 2 3 nv = u u v = 1 1 2 2 3 3 nv = u; u v = 1 2 3 1 2 3 Initializing Variables EESC nI

15、nitialization using built-in functions nzeros() nx = zeros(2) x = 0 0 0 0 nz = zeros(2,3) z = 0 0 0 0 0 0 nones(), size(), length() ny = zeros(1,4) y = 0 0 0 0 nt = zeros( size(z) ) t = 0 0 0 0 0 0 Initializing Variables EESC nInitialization using keyboard input ninput() nvalue = input( Enter an inp

16、ut value: ) Enter an input value: 1.25 value = 1.2500 nname = input( What is your name: , s ) What is your name: Selim name = Selim Initializing Variables EESC nInitialization nc(:,:,1)=1 2 3; 4 5 6; c(:,:,2)=7 8 9; 10 11 12; n whos Name Size Bytes Class c 2x3x2 96 double array n c c(:,:,1) = 1 2 3

17、4 5 6 c(:,:,2) = 7 8 9 10 11 12 Multidimensional Arrays(多维数组)(多维数组) EESC nStoring in Memory nTwo-dimensional : Column major order nMultidimensional Arrays : array subscript incremented first, second, third, (1,1,1), (2,1,1), (1,2,1), (2,2,1), (1,1,2), (2,1,2), (1,2,2), (2,2,2) nAccessing Multidimens

18、ional arrays with a Single Subscript nThe elements will be accessed in the order in which they were allocated in memory n c(5) Multidimensional Arrays EESC nArray indices start from 1 nx = -2 0 9 1 4 ; nx(2) ans = 0 nx(4) ans = 1 nx(8) ? Error nx(-1) ? Error Subarrays(子数组)(子数组) EESC ny = 1 2 3; 4 5

19、6 ; ny(1,2) ans = 2 ny(2,1) ans = 4 ny(2) ans = 4 (column major order) Subarrays EESC ny = 1 2 3; 4 5 6 ; ny(1,:) ans = 1 2 3 ny(:,2) ans = 2 5 ny(2,1:2) ans = 4 5 ny(1,2:end) ans = 2 3 ny(:,2:end) ans = 2 3 5 6 Subarrays EESC nx = -2 0 9 1 4 ; nx(2) = 5 x = -2 5 9 1 4 nx(4) = x(1) x = -2 5 9 -2 4 n

20、x(8) = -1 x = -2 5 9 -2 4 0 0 -1 Subarrays EESC ny = 1 2 3; 4 5 6 ; ny(1,2) = -5 y = 1 -5 3 4 5 6 ny(2,1) = 0 y = 1 -5 3 0 5 6 ny(1,2:end) = -1 9 y = 1 -1 9 0 5 6 Subarrays EESC ny = 1 2 3; 4 5 6; 7 8 9 ; ny(2:end,2:end) = 0 y = 1 2 3 4 0 0 7 0 0 ny(2:end,2:end) = -1 5 ? Error ny(2,1 3) = -2 y = 1 2

21、 3 -2 0 -2 7 0 0 Subarrays EESC npi: value up to 15 significant digits ni, j: sqrt(-1) nInf: infinity (such as division by 0) nNaN: Not-a-Number (such as division of zero by zero) nclock: current date and time as a vector ndate: current date as a string (e.g. 16-Feb- 2004) neps: epsilon nans: defaul

22、t variable for answers Special Values(特殊值)(特殊值) EESC nChanging the data format nvalue = 12.345678901234567 format short 12.3457 long 12.34567890123457 short e 1.2346e+001 long e 1.234567890123457e+001 rat 1000/81 compact loose Displaying Data(数据显示)(数据显示) EESC nThe disp( array ) function ndisp( Hello

23、 ); Hello ndisp(5); 5 ndisp( 四川师范四川师范 大学大学 ); 四川师范大学四川师范大学 nname = Selim; disp( Hello name ); Hello Selim Displaying Data EESC nThe num2str() and int2str() functions nd = num2str(02) -Mar- num2str(2006) ; ndisp(d); 2-Mar-2006 nx = 23.11; ndisp( answer = num2str(x) ); answer = 23.11 ndisp( answer = i

24、nt2str(x) ); answer = 23 Displaying Data EESC nThe fprintf( format, data ) function n%dinteger n%ffloating point format n%eexponential format nnskip to a new line nttab character Displaying Data EESC nfprintf( Result is %d, 3 ); Result is 3 nfprintf( Area of a circle with radius %d is %f, 3, pi*32 )

25、; Area of a circle with radius 3 is 28.274334 nx = 5; nfprintf( x = %3d, x ); x = 5 nx = pi; nfprintf( x = %0.2f, x ); x = 3.14 nfprintf( x = %6.2f, x ); x = 3.14 nfprintf( x = %dny = %dn, 3, 13 ); x = 3 y = 13 Displaying Data EESC nsave filename var1 var2 nsave homework.mat x y binary nsave x.dat x

26、 ascii ascii nload filename nload filename.mat binary nload x.dat ascii ascii Data Files(数据文件)(数据文件) EESC Scalar Operations(标量运算)(标量运算) nvariable_name = expression; nadditiona + b a + b nsubtractiona - b a - b nmultiplicationa x b a * b ndivisiona / b a / b nexponentab a b EESC nx = 3 * 2 + 6 / 2 nx

27、 = ? nProcessing order of operations is important nparenthesis (starting from the innermost) nexponentials (left to right) nmultiplications and divisions (left to right) nadditions and subtractions (left to right) nx = 3 * 2 + 6 / 2 nx = 9 Scalar Operations(标量运算)(标量运算) EESC Matrix Operations(矩阵运算)(矩

28、阵运算) nScalar-matrix operations na = 1 2; 3 4 a = 1 2 3 4 n2 * a ans = 2 4 6 8 na + 4 ans = 5 6 7 8 nElement-by-element operations na = 1 0; 2 1 ; nb = -1 2; 0 1 ; na + b ans = 0 2 2 2 na .* b ans = -1 0 0 1 EESC nMatrix multiplication: C = A * B nIf nA is a p-by-q matrix nB is a q-by-r matrix then n

29、C will be a p-by-r matrix where q k jkBkiAjiC 1 ),(),(),( Matrix Operations EESC nMatrix multiplication: C = A * B 333231 232221 131211 aaa aaa aaa A 3231 2221 1211 bb bb bb B )()( )()( )()( 323322321231313321321131 322322221221312321221121 321322121211311321121111 babababababa babababababa babababa

30、baba C Matrix Operations EESC nExamples na = 1 2; 3 4 a = 1 2 3 4 nb = -1 3; 2 -1 b = -1 3 2 -1 na .* b ans = -1 6 6 -4 na * b ans = 3 1 5 5 Matrix Operations EESC nExamples na = 1 4 2; 5 7 3; 9 1 6 a = 1 4 2 5 7 3 9 1 6 nb = 6 1; 2 5; 7 3 b = 6 1 2 5 7 3 nc = a * b c = 28 27 65 49 98 32 nd = b * a

31、? Error using = * Inner matrix dimensions must agree. Matrix Operations EESC nIdentity matrix: I nA * I = I * A = A nExamples na = 1 4 2; 5 7 3; 9 1 6 ; nI = eye(3) I = 1 0 0 0 1 0 0 0 1 na * I ans = 1 4 2 5 7 3 9 1 6 Matrix Operations EESC nInverse of a matrix: A-1 nA A-1 = A-1 A = I nExamples na =

32、 1 4 2; 5 7 3; 9 1 6 ; nb = inv(a) b = -0.4382 0.2472 0.0225 0.0337 0.1348 -0.0787 0.6517 -0.3933 0.1461 na * b ans = 1.0000 0 0 0.0000 1.0000 0 0 -0.0000 1.0000 Matrix Operations EESC nMatrix left division: C = A B nUsed to solve the matrix equation A X = B where X = A-1 B nIn MATLAB, you can write

33、 nx = inv(a) * b nx = a b (second version is recommended) Matrix Operations EESC nExample: Solving a system of linear equations nA = 4 -2 6; 2 8 2; 6 10 3 ; nB = 8 4 0 ; nX = A B X = -1.8049 0.2927 2.6341 03106 4282 8624 zyx zyx zyx 0 4 8 3106 282 624 z y x Matrix Operations EESC nMatrix right divis

34、ion: C = A / B nUsed to solve the matrix equation X A = B where X = B A-1 nIn MATLAB, you can write nx = b * inv(a) nx = b / a (second version is recommended) Matrix Operations EESC Initializing Vectors(矢量初始化)(矢量初始化) ncolon operator nx = 1:2:10 x = 1 3 5 7 9 ny = 0:0.1:0.5 y = 0 0.1 0.2 0.3 0.4 0.5

35、EESC Initializing Vectors nlinspace(x1,x2) generates a row vector of 100 linearly equally spaced points between x1 and x2 nlinspace(x1,x2,N) generates N points between x1 and x2 nx = linspace(10,20,5) x = 10.00 12.50 15.00 17.50 20.00 nlogspace(x1,x2) can be used for logarithmically equally spaced p

36、oints EESC Vector Operations(矢量运算)(矢量运算) nScalar-vector operations nx = 1:5 x = 1 2 3 4 5 ny = 2 * x scalar multiplication y = 2 4 6 8 10 nz = x + 10 scalar addition z = 11 12 13 14 15 EESC Vector Operations nVector-vector operations (element-by-element operations) nx = 1 2 3 4 5 ; y = 2 -1 4 3 -2 ;

37、 nz = x + y z = 3 1 7 7 3 nz = x .* y z = 2 -2 12 12 -10 nz = x ./ y z = 0.5000 -2.0000 0.7500 1.3333 -2.5000 EESC Vector Operations nVector-vector operations (element-by-element operations) nz = x . y nz = 1.00 0.50 81.00 64.00 0.04 nUse .*, ./, . for element-by-element operations nVector dimension

38、s must be the same EESC Built-in Functions(建立函数)(建立函数) nresult = function_name( input ); nabs, sign nlog, log10, log2 nexp nsqrt nsin, cos, tan nasin, acos, atan nmax, min nround, floor, ceil, fix nmod, rem nhelp function_name EESC nOptional Results Can return more than one result nUsing MATLAB Func

39、tion with Array Input nYou can call built-in functions with array inputs nThe function is applied to all elements of the array nThe result is an array with the same size as the input array Built-in Functions EESC nExamples: nx = 3 -2 9 4 -5 6 2 ; nabs(x) ans = 3 2 9 4 5 6 2 nsin( 0 pi/6 pi/4 pi/3 pi

40、/2 ) ans = 0 0.5000 0.7071 0.8660 1.0000 na = 1:5; nlog(a) ans = 0 0.6931 1.0986 1.3863 1.6094 Built-in Functions EESC Useful Commands(重要命令)(重要命令) nhelp command Online help nlookfor keyword Lists related commands nwhich Version and location info nclear Clears the workspace nclc Clears the command wi

41、ndow ndiary filename Sends output to file ndiary on/off Turns diary on/off nwho, whos Lists content of the workspace nCtrl+c Aborts operation n Continuation n% Comments EESC Program Design EESC Creating MATLAB Scripts(创建脚本)(创建脚本) nChoose FileNewM-file from the menu nUse the editor to write your prog

42、ram nDocument your program using comments that include nShort note about what your program does nShort note about how it works nAuthor information nDate information nVersion information EESC Creating MATLAB Scripts % Script file: temp_conversion.m % % Purpose: % To convert an input temperature from

43、degrees Fahrenheit to % an output temperature in kelvins. % % Record of revisions: % Date Programmer Description of change % = = = % 12/01/97 S. J. Chapman Original code % % Define variables: % temp_f - Temperature in degrees Fahrenheit % temp_k - Temperature in kelvins % Prompt the user for the inp

44、ut temperature. temp_f = input(Enter the temperature in degrees Fahrenheit: ); % Convert to kelvins. temp_k = (5/9) * (temp_f - 32) + 273.15; % Write out the result. fprintf(%6.2f degrees Fahrenheit = %6.2f kelvins.n, . temp_f,temp_k); EESC Top-down(自上而下)(自上而下) Program Design Start State the problem

45、 Define inputs and outputs Design the algorithm Convert algorithm into MATLAB statements Test the resulting program End Decomposition Stepwise refinement EESC Pseudocode(伪指令)(伪指令) nA hybrid mixture of MATLAB and English for defining algorithms nIndependent of any programming language so it can be ea

46、sily converted to any programming language nExample pseudocode: Prompt user to enter temperature in degrees Fahrenheit Read temperature in degrees Fahrenheit (temp_f) temp_k (in Kelvins) (5/9) * (temp_f 32) + 273.15 Write temperature in degree Kelvins EESC Testing(测试)(测试) nTest individual subtasks:

47、unit testing nAdd tested components one by one and test them together: build nAlpha release nBeta release nTest for all legal input data sets: standard data sets, ground truth EESC Top-down Program Design nProblem: write a program that takes the radius and height (in meters) of a cylinder tank and t

48、he amount of water (in m3) from the user and output the amount of extra space (in m3) in the tank. nInput: nradius and height namount of water nOutput: nextra space EESC Top-down Program Design nDesign: nGet radius of the tank base from the user nGet the height of the tank from the user nGet the amo

49、unt of water nCalculate the amount of extra space nWrite the result nStep 4 is not clear enough, refine it: nCalculate the capacity of the tank (pi * radius2 * h) nextra space capacity - water EESC Top-down Program Design nCode: r = input(Enter the radius of the tank base:); h = input(Enter the heig

50、ht of the tank:); water = input(Enter the amount of water:); capacity = pi * r2 * h; space = capacity - water; fprintf(There is %f m3 extra space in the tank, space); EESC Top-down Program Design nTesting: Enter the radius of the tank base:2 Enter the height of the tank:5 Enter the amount of water:1

51、0 There is 52.831853 m3 extra space in the tank nContinue testing: Enter the radius of the tank base:2 Enter the height of the tank:5 Enter the amount of water:100 There is -37.168147 m3 extra space in the tank EESC Branches(分支)(分支) nBranches are used to select and execute specific sections of the c

52、ode while skipping other sections nSelection of different sections depend on a condition statement nWe will learn: nif statement nswitch statement EESC Branches: “if” Statement if ( condition ), statement 1 statement 2 . end condition statement group true false statement group EESC Branches: “if” St

53、atement nConditions can be: nany real value (0 is false, non-zero is true) ncombination of relational and logical operators ne.g. ( x 0 ) end nif ( ( grade 100 ) ), disp( Grade must be in 0,100 range ); end nif isinf( result ), disp( Result is infinite ); end EESC Branches: “if-else” Statement if (

54、condition ), statement 1 statement 2 . else statement 1 statement 2 . end condition statement group 1 truefalse statement group 2 statement group 1 statement group 2 EESC Branches: “if-elseif-else” Statement if ( condition 1 ), statement 1 statement 2 . elseif ( condition 2 ), statement 1 statement

55、2 . else statement 1 statement 2 . end statement group 1 condition 1 statement group 1 truefalse condition 2 statement group 2 statement group 3 truefalse statement group 2 statement group 3 EESC Branching Examples nExample: Finding roots of the quadratic equation “ax2 + bx + c = 0” nPseudocode: nd

56、= b2 4ac nif d 0, two real roots else if d = 0, two identical roots else two complex roots EESC Branching Examples nExample: Assigning letter grades How can we compute the letter corresponding to a given numeric grade? RangeGrade 100 grade 95A 95 grade 86B 86 grade 76C 76 grade 66D 66 grade 0F EESC

57、Branching Examples nLetter grade example: if ( grade 95 ), disp( Grade is A ); elseif ( grade 86 ), disp( Grade is B ); elseif ( grade 76 ), disp( Grade is C ); elseif ( grade 66 ), disp( Grade is D ); else disp( Grade is F ); end EESC Branching Examples if ( grade 95 ), disp( Grade is A ); else if

58、( grade 86 ), disp( Grade is B ); else if ( grade 76 ), disp( Grade is C ); else if ( grade 66 ), disp( Grade is D ); else disp( Grade is F ); end end end end nested if statements EESC Branches: “switch” Statement switch ( expression ), case value 1, statement 1 statement 2 . case value 2, statement

59、 1 statement 2 . . end statement group 1 statement group 2 expression is a scalar or string constant EESC Branches: “switch” Statement switch ( expression ), case value set 1, statement 1 statement 2 . case value set 2, statement 1 statement 2 . . otherwise, statement 1 statement 2 . end statement g

60、roup 1 statement group 2 optional statement group that is executed if none of the cases is satisfied EESC Branching Examples nExample: Odd or even numbers a=10; switch a5 case 1 a=6 case 0 a=0 end EESC Question: Season Judge %function switch_case(month) switch month case 3,4,5 season=spring case 6,7

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论