《chapter 1matlab programming for engineerszyn.ppt》由会员分享,可在线阅读,更多相关《chapter 1matlab programming for engineerszyn.ppt(40页珍藏版)》请在三一办公上搜索。
1、Matlab Programming for Engineers,Room 414,EE/AC,SYSU,Emails:ynzhangieee.org,Yunong Zhang(张雨浓),http:/,What is Matlab?Why do we learn Matlab?How do we learn Matlab?,Introduction,What have you learned from Matlab?,A Brief History of Matlab,Engineering and scientific applications involve a lot of number
2、 crunching.For many years,the main language for this was FORTRAN-first high level programming language,and especially designed for numerical computing.Heres a Fortran code to solve ax2+b x+c=0:,C Solve a quadratic equation(this is a comment).DESC=B*B-4*A*C IF(DESC.LT.0.0)GOTO 10 DESC=SQRT(DESC)X1=(-
3、B+DESC)/(2.0*A)X2=(-B-DESC)/(2.0*A)WRITE(6,*)SOLUTIONS ARE,X1,AND,X2 RETURN 10 WRITE(6,*)EQUATION HAS COMPLEX ROOTS RETURN,Problems using FORTRAN,Number crunching on a computer can be tricky.Problems that occur are:loss of precision and inaccurate results:X=0.1Y=1.0-10*X Y should equal 0,but probabl
4、y does not!underflow and overflow:X=1.0E20,X*X-too big!efficient coding of algorithms not always obvious DO 10 N=1,100000 10 Y(N)=SQRT(2.0)*X(N)-less efficient!cf.inefficientprogramming errors!,Solving a Linear System in Fortran,Heres a Fortran code to solve a linear system b=A*x,solve for x.It does
5、nt check for degeneracy or zeros.,C Solve B=A*X for X.C N is dimension of vectors and matrixC Does not use row interchange,scaling.SUBROUTINE LINSYS(N,A,X,B,TMP)INTEGER N DOUBLE PRECISION A(N,N),X(N),B(N)DOUBLE PRECISION TMP(N),RATIOC.Forward elimination DO 13 J=1,N-1 DO 12 I=J+1,N RATIO=-A(I,J)/A(J
6、,J)A(I,*)=A(I,*)+RATIO*ROW(J,*)DO 11 K=J+1,N 11 A(I,K)=A(I,K)+RATIO*A(J,K)A(I,J)=0.0 X(I)=X(I)+RATIO*X(J)12 CONTINUE 11 CONTINUE Continued.,C.Backwards substitution X(N)=X(N)/A(N,N)DO 21 I=N-1,1,-1 TMP=X(I)DO 20 J=I+1,N 20 TMP=TMP-A(I,J)*X(J)X(I)=TMP/A(I,I)21 CONTINUE RETURN END,This is just a small
7、 example.A full program may be thousands of lines long.,Need for Numerical Libraries,The U.S.government recognized these problems,and the inefficiency of many engineers all writing the same algorithms.again and again.So,they commissioned numerical analysts to write good quality algorithms for common
8、 tasks.Make the results freely available as libraries of subroutines than anyone can use in their programs.Libraries are available at:lib.org,Examples of Numerical Libraries,BLAS(Basic Linear Algebra Subroutines):operations on vectors,like adding to vectors,dot product,norm.LINPACK:linear algebra su
9、broutines for vector-matrix operations,solving linear systems,factoring a matrix,inverting a matrix.Later replaced by LAPACK.EISPACK:compute eigenvalues and eigenvectors of matrices.Example:solve A*x=b using LINPACK,C.factor the A matrix CALL SGEFA(A,N,N,IPVT,INFO)C.copy B vector into X vector CALL
10、SCOPY(N,B,1,X,1)C.solve the system of equations CALL SGESL(A,N,N,IPVT,X,0),Still Not Easy Enough!,Cleve Moler,mathematician,C.S.Professor,and co-author of LINPACK,thought this is still too much work:write FORTRAN,compile,debug,compile,run.He wanted to give students easy access to LINPACK.So,he wrote
11、 MATLAB(Matrix Laboratory).interactiveeasy input,easy outputoperations on a whole vector or matrix at onceExample:solve b=A*x in Matlab.x=A b,When?,Immediate Popularity!,MATLAB quickly became quite popular and used for both teaching and research.It was also free.An engineer,Jack Little,saw Matlab du
12、ring a lecture by Cleve Moler at Stanford University.He saw the commercial potential and(with permission)rewrote Matlab in Cadded M-files(stored programs)added many new features and librariesfounded The Mathworks to market it.,When?,Software principles.,Matlab illustrates some useful design concepts
13、 for software.,FORTRAN/C/JAVA Compiler,Linear Algebra Libraries,Matlab,Matlab Toolkits,Matlab M-Files,Standard base platform,Modular,reusable software components,Extensible using Toolkits or user-contributed programs called M-files.,Interactive user interface;hides boring details,Matlab Today,Millio
14、ns of users!A standard tool in both professional and academic useToolboxes providing functions for many applications:control systemsidentificationneural networksbio-informaticsstatistics and time-series analysisCan do symbolic mathematics,too.Simulink:GUI based simulation tool,Matrix LaboratoryHigh-
15、performance language for technical computingComputation,visualization,and programming in an easy-to-use environment,Summary,University-level computer-programming language,cf.JAVA/C/Fortran/VB/and machine-level CPA,Typical Applications,Math and computationAlgorithm developmentModelling,simulation,and
16、 prototypingData analysis,exploration,and visualizationScientific and engineering graphicsApplication development,including Graphical User Interface building,Applications:Example 1,Applications:Example 1(cont.),Solution of ODE,x=3(y-x)y=-xz+26.5x-y z=xy-z,Butterfly Effect,ODE45 function in Matlab,Ap
17、plications:Example 2,Applications:Example 2(Cont.),Loading an image:a=imread(picture.jpg);imshow(a);,Applications:Example 2(Cont.),Show RED plane:a(:,:,2:3)=0;imshow(a);,Loading an image:a=imread(picture.jpg);imshow(a);,Applications:Example 2(Cont.),Show GREEN plane:a(:,:,1 3)=0;imshow(a);,Applicati
18、ons:Example 2(Cont.),Show BLUE plane:a(:,:,1:2)=0;imshow(a);,Why?,Data Analysis,Applications:Example 3,Stock market,Predicted by Neural Network Toolbox in MatlabBP,RBF Neural NetworkTraining the network:train function,Applications:Example 3(cont.),Predicting example,Applications:Example 3(cont.),De-
19、noise example,Applications:Example 3(cont.),Advantages of Matlab,Ease to Use Interpreted Language,like Basic;Integrated development environment;Online documentation,manuals,and demos,etc.Platform Independence Independence of operation systems and computers:Windows 95/98/ME/NT/2000/XP,Unix,Linux,and
20、super-computers,Predefined Functions Extensive library of predefined functions;such as arithmetic mean,standard deviation,median,etc;Toolboxes such as Communications,Control systems,Signal Processing,Graphical User Interface Interactive;Easier to use for inexperienced users,Advantages of Matlab(Cont
21、.),How to define?,Slow for some kinds of processes Interpreted Language Not designed for large-scale system developmentHigh cost Expensive for individuals,Disadvantages of Matlab,Matlab Environment,Matlab desktop includes the following windows:The Command Window;The Command History Window;Launch Pad
22、;Workspace;Current Directory,Matlab Environment(Cont.),The Command Window,Allow users to enter commands at/under the command promptMatlab calculates the answer once the Enter key is pressedEllipsis()is used if a statement is too long.,x1=1+1/2+1/3+1/4+1/5+1/6,x1=1+1/2+1/3+1/4+1/5+1/6,cf.ellipse!,The
23、 Command History Window,Display a list of the commands typed beforeRe-execute a command by double-clicking itDelete a command by right clicking it and selecting the item”Delete Section”from the popup menu,What if?,The Launch Pad,A tree of documentation,demos,and related tools installed here,The Work
24、space,Computer Memory occupied by variables and arrays used by Matlabwhos List variables and arrays in the current workspace,The Edit/Debug and Figure Windows,An Edit/Debug window is used to create a new.m file or to modify an existing one.Click Toolbar icon to create a new one Click Toolbar icon to
25、 modify an existing one,A Figure Window is used to display Matlab graphics.,Important Commands,demo:To run Matlabs built-in demonstrationsclc:To clear the contents of the Command Windowclf:To clear the contents of the current figure windowclear:To clear the variables in the workspacec(ctrl+c):abort
26、command!:To execute commands of computers operating systemdiary:to copy all input and output displayed in the Command Window diary off:to suspend input into the diary file diary on:to resume input again,!copy jzsf.m jzsftest.m,Searching and locating files,1)It looks for the name as a variable.If it
27、is a variable,Matlab displays the current contents of the variable.2)It checks to see if the name is a built-in function or command.If it is,Matlab executes that function or command.3)It checks to see if the name is an M-file in the current directory.If it is,Matlab executes that function or command
28、.4)It checks to see if the name is an M-file in any directory in the search path.If it is,Matlab executes that function or command.,Searching and locating files(cont.),Remember in mind Never use a variable with the same name as a Matlab function or command.Otherwise,that function or command will bec
29、ome inaccessible.Never create an m-file with the same name as a Matlab function or command.,sin=5;sin(1)=?,Answer:5 Wrong!,which To find out which version of the file,and where it is located.,Searching and locating files(cont.),which crossC:MATLAB6p5toolboxmatlabspecfuncross.m,Getting Help,Get help
30、in three ways in Matlab,Click Toolbar icon to start the Help BrowserType help specificfunction in Command Window,help sin SIN Sine.SIN(X)is the sine of the elements of X.,Type lookfor specificfunction in Command Window,Getting Help(cont.),Help Browser:Allow full access to the entire Matlab documenta
31、tion sethelp functionname:You must know the name of the function to get help about itlookfor functionname:Search for a given string in the first comment line of every Matlab function,and display all matches,help a a.m not found.,lookfor aADDPATH Add directory to search path.BINPATCH Patch binary file.CD Change current working directory.CLEAR Clear variables and functions from memory.DATATIPINFO Produce a short description of a variable.DBCLEAR Remove breakpoint.DBDOWN Change local workspace context.DBSTACK Display function call stack.DBSTATUS List all the breakpoints.,