《Matlab预定义函数.ppt》由会员分享,可在线阅读,更多相关《Matlab预定义函数.ppt(40页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、Matlab与科学计算与科学计算计算机学院计算机学院计算机学院计算机学院 刘咏梅刘咏梅刘咏梅刘咏梅Email:Email:1第四章 MATLAB编程(预定义函数预定义函数)Introduction to MATLAB MATLAB Basics of Numerical Computing MATLAB Programming(branching and Loops)MATLAB Programming(Predefined Functions)MATLAB Graphic and Image ProcessingScientific Computing using MATLAB 2本章学习的
2、目标:Introduction to Matlab Functionsbuilt in functions and user defined functionsOptional ArgumentsSharing Data Using Global MemoryPreserving Data Between Calls to a FunctionFunction FunctionsSubfunctions3FunctionsFunctions are more complex than scriptsFunctions have their own local variablesFunction
3、s return output as specified,and can accept input as specified4Why we use functions?Independent Testing of Sub-Tasks:Each task is an independent unit that can be tested separately(unit testing).Reusable Code:Within the same program(the code is not repeated).It can be used in another program.Isolatio
4、n from unintended side effects:Isolation of function variables from the main program variables.The input and the output variables are specified clearly.5Syntax of Matlab FunctionsUser defined functions behave just like built in functions.All functions have a similar syntax,whether they are built-in
5、functions or user-defined functions.NameInputOutputA=cos(x)6How to call functions?The functions can be called directly in the command window,or by any other program or function.Very important:if the input variables are changed in the functions they will not change in the main program(PASS-BY-VALUE S
6、CHEME)7Built in FunctionsBuilt in functions allow us to reuse computer code for calculations that are performed frequently.For example,suppose there were no built in sine function in MATLAB and you will do a lot of trigonometric calculations involving the sine of an angle.Weve already become familia
7、r with a number of MATLAB built in functions like sin(x)or plot(x,y)for example.8Some examples of Built in FunctionsExponential(指数)exp(x)exponential of x(ex)sqrt(x)square root of xLogarithmic(对数)log(x)natural logarithm(ln x)log10(x)log2(x)9Some examples of Built in FunctionsNumeric(数值)fix(x)round to
8、 nearest integer towards 0round(x)round to nearest integersign(x)+1,0 or-1 rem(x,y)Finds remainder of x/yComplex(复数)abs(x)absolute value angle(x)phase angle in complex plane conj(x)conjugate of x imag(x)imaginary part of xreal(x)real part of x10Builtin Functions for vectorsmax(x)returns largest valu
9、e in vector xa,b=max(x)returns largest value in a and index where found in bmax(x,y)x and y arrays of same size,returns vector of same length with larger value from corresponding positions in x and ymax(3 5 2,6 4 8)ans=6 5 8same type of functions are available for min11Builtin Functions for vectorss
10、ort(x)sort in ascending or descending ordermean(x)average or mean valuemedian(x)median valuesum(x)sum of elements of xprod(x)product of elements of xcumsum(x)returns vector of same size with cumulative sum of x i.e.x=4,2,3 returns 4,6,9cumprod(x)returns vector of same size with cumulative products i
11、n vector of same sizei.e.x=4,2,3 returns 4,8,2412Builtin functions applied to matricesMatrices(arrays)are stored in column major formWhen builtin functions for vectors are applied to a matrix function operates on columns and returns a row vector13Builtin functions applied to matricessum(0 1 2;3 4 5)
12、ans=3 5 7prod(0 1 2;3 4 5)ans=0 4 10cumsum(0 1 2;3 4 5)ans=0 1 2 3 5 7cumprod(0 1 2;3 4 5)ans=0 1 2 0 4 10sort(9 1 2;3 2 4)ans=3 1 2 9 2 414User-defined FunctionsYou can use user defined functions in your programs just as you would use MATLABs built in functions.User defined functions help you write
13、 more compact programs and write complex programs into shorter ones that are easier to debug and get running.15User-defined FunctionsUser-defined functions must start with a function definition line.The definition line containsThe word functionA variable(variables)that defines the function outputA f
14、unction nameA variable(variables)used for the input argumentfunction output=poly(x)The above line of codes defines a function named poly.16A simple example of user-defined functionsThe function name must be the same as the file name17You can use your user defined functions from the Command Window or
15、 from a M-file program.18When x is a vectorConsider the following,A=1,2,5;%A is a 3-element row vector y=2*poly(A)y=14 82 982In the statement y=2*poly(A)above,the user defined function poly is called which evaluates the polynomial at each point in the input row vector.Then,each value is multiplied b
16、y 2,resulting in the row vector called y having the values 14,82,982.19Comments for FunctionsThe comment lines immediately after the first line are returned when you query the help function2021User defined functions mayHave more than one input variable,function s=f(x,y,z).This function has three inp
17、ut variables.Have more than one output variable,function out1,out2=f(x)is a function with one input variable and two output variables.Input and output variables can be scalars,vectors or matrices.Within the body of the function,there needs to be one assignment statement for each output variable.22Lo
18、cal VariablesAny variables used within a function are called local variables.These variables do not appear in the Workspace Window and are not available for the main program to access.The output variable names used in the function statement and in the body of the function are also local variables.Th
19、e input variables are local variables also.23Local VariablesVariables defined in an M-file function,only have meaning inside that programThe only way to communicate between functions and the workspace,is through the function input and output arguments24x,y,a,and output are local variables to the g f
20、unctionWhen the g function is executed,the only variable created is determined in the command window(or script M-file used to execute a program)ans is the only variable created25Optional ArgumentsFor example:plot functionx=0:pi/100:2*pi;y1=sin(2*x);y2=2*cos(2*x);plot(x,y1,x,y2);x=0:pi/100:2*pi;y1=si
21、n(2*x);y2=2*cos(2*x);plot(x,y1);hold on;plot(x,y2);26Optional Argumentsmax(x)returns largest value in vector xa,b=max(x)returns largest value in a and index where found in bmax(x,y)x and y arrays of same size,returns vector of same length with larger value from corresponding positions in x and ysame
22、 type of functions are available for min27Optional Arguments(Input and Output)Optional Arguments(Input and Output)Optional output Optional input 28Determine the number of input and output variablesTwo built in functions let you determine the number of input and output variables in any function,for f
23、unction s=f(x)nargin(f)returns in our case,ans=1 since f has one input argument,andnargout(f)also returns ans=1 in our case because f has only one output variable.nargin:determines the number of input argumentsnargout:determines the number of output arguments29Global VariablesRemember variable names
24、 used within a function are local variables,they do not appear in the Workspace window of the main program.It is possible to define a Global Variable that is then common to both the main program and the function.It is recommended not to do this.Although it is possible to define global variables,it i
25、s a bad idea!30Sharing Data Using Global MemoryGlobal memory is a special memory that can be accessed from any workspace.Syntax:global var1 var2 var3 Remark:Each global variable must be declared to be global before it is used for the first time in a function.Better to be the first statement in the f
26、unction after the initial comments.31Preserving Data Between Calls to a FunctionEach time the function is finished,data in the workspace is destroyed.To make some variables persistent for the next function calls,use the persist command.Special type of memory that can be accessed only from the same f
27、unction.Syntax:persistent var1 var2 var3 32Preserving Data Between Calls to a FunctionPreserving Data Between Calls to a FunctionExercise:running averages and standard deviations.User must enter the number of values in data set,and then enter value by value.Each time he enters a value the program ca
28、lls the function and then displays the current output(average and standard deviation).Use this table to test your program.33Function FunctionsInput variables of this type of function contains the name of other functions.Example,fzero函数用函数用于找到传递给于找到传递给它的函数值为它的函数值为0时的自变量时的自变量34Function Functions对字符串进行
29、求值对字符串进行求值,像在像在command窗口中键入的一样窗口中键入的一样35Function Functions对函数进行求值对函数进行求值36SubfunctionsNormal/principle function:The m-file name should be mystatsSubfunction:Accessible only by the other functions in the same fileFunctions in the same file37第四章 作业Exercises5.1,5.2,5.3第四章需要提交实验报告实验目的掌握Matlab常用内置函数的使用方法掌握Matlab编程中的用户自定义函数38实验(3)Matlab编程(预定义函数)本次实验课,完成下面的各项实验:(1)编写自己的排序函数,该函数可以对一个行向量中的各元素进行排序。并利用sort函数进行检验。(2)编写一函数,计算一行向量中各元素的均值和标准差。(3)编写一函数,用于画任意半径、任意色彩的圆。(4)编写一函数,用于求正弦函数的导数,定义域的范围为0,2*pi,并用内置函数cos(x)进行验证。(具体见习题5.16)39The End of Chapter Four!Lets go on with Chapter Five!40
限制150内