MATLAB's function files, special forms of functions, and program debugging and optimization

1. Function file

  • Many times we hope to write specific algorithms in the form of functions to improve the reusability of programs and the efficiency of program design.
  • The function file defines the corresponding relationship between output parameters and input parameters to facilitate external calls. In fact, the standard functions provided by MATLAB are all defined by function files.

1. The basic structure of the function file

  • A function file is guided by a function statement, and its basic structure is as follows:
function 输出形参表=函数名(输入形参表)
注释说明部分
函数体语句
  • Among them, the line starting with function is a guide line, which means defining a function. The naming rules for function names are the same as variable names.
  • When the function is defined, the input and output parameters do not allocate storage space, so they are called formal parameters, or formal parameters for short. When there are multiple formal parameters, the formal parameters are separated by commas to form a formal parameter table. When there are more than one output parameters, they should be enclosed in square brackets to form an output matrix.
  • illustrate:
  • (1) About the function file name. The function file name usually consists of the function name plus the extension .m, but the function file name and function name can also be different. When the two are different, MATLAB ignores the function name and uses the function file name when calling. For the convenience of understanding and memory, it is generally recommended that the function file name and function name be unified.
  • (2) About the notes section. Notes include the following 3 parts.
  • ① The first comment line beginning with % immediately after the leading line of the function file. This line generally includes the function file name in uppercase and a brief description of the function function, which is used for lookfor keyword query and help online help.
  • ② The first comment line and subsequent continuous comment lines. It usually includes information such as the meaning of the function input and output parameters and the description of the calling format, which constitutes the entire online help text.
  • ③ A comment line separated from the online help text by a blank line. Including the information of writing and modifying function files, such as author, modification date, version, etc., which are used for software file management.
  • (3) Regarding the return statement. If a return statement is inserted in the function file, the execution of the function will end when the statement is executed, and the program flow will go to the place where the function is called. Usually, the return statement may not be used in the function file. At this time, the called function returns automatically after the execution is completed.
  • For example, we write a function file to find the area and perimeter of a circle with radius r.
  • The function file is as follows:
function [s,p] = fcircle(r)
% CIRCLE calculate the area and perimeter of a circle of radii r
% r    圆半径
% s    圆面积
% p    圆周长
% 2023515日编

s=pi*r*r;
p=2*pi*r;
  • Save the above function file with the file name fcircle.m, and then call the function in the MATLAB command line window.
>> [s,p]=fcircle(10)

s =

  314.1593


p =

   62.8319

  • Use the help command or lookfor command to display the content of the comment section, and its function is consistent with the help information of general MATLAB functions.
  • Use the help command to query the comment description of the fcircle function.
>> help fcircle
  CIRCLE calculate the area and perimeter of a circle of radii r
  r    圆半径
  s    圆面积
  p    圆周长
  2023515日编

  • Then use the lookfor command to search and list all the files whose first comment line includes the specified keyword in the search path of MATLAB.
>> lookfor perimeter
fcircle                        - CIRCLE calculate the area and perimeter of a circle of radii r

2. Function call

2.1 Format of function call

  • After the function file is created, the function can be called, and the calling format is as follows:
    [输出实参表]=函数名(输入实参表)
  • When calling a function, the function input and output parameters are called actual parameters, or actual parameters for short. It should be noted that the order and number of actual parameters when the function is called should be consistent with the order and number of formal parameters when the function is defined, otherwise an error will occur. When the function is called, the actual parameter is passed to the corresponding formal parameter first, so as to realize the parameter passing, and then execute the function of the function.
  • For example, we use the function file to realize Cartesian coordinates ( x , y ) (x, y)(x,y ) and polar coordinates( ρ , θ ) (\rho,\theta)( p ,θ ) between ρ = x 2 + y 2 \rho =\sqrt{x^{2}+y^{2}}r=x2+y2 θ = arctan ⁡ (y/x) \theta =\arctan (y/x)i=arctan ( y / x )
  • First write the function file tran.m.
function [rho,theta] = tran(x,y)
rho=sqrt(x*x+y*y);
theta=atan(y/x);
end
  • Then call the function file tran.m in the script file.
x=input('x= ');
y=input('y=? ');
[rho,theta]=tran(x,y);
disp(['rho=',num2str(rho)])
disp(['theta=',num2str(theta)])
  • Finally, run the script file in the command line window.
x= 45
y= 45
rho=63.6396
theta=0.7854
  • In fact, MATLAB provides functions for converting between direct coordinates and polar coordinates, as follows:
  • (1) [th,r]=cart2pol(x,y) is to convert rectangular coordinates to polar coordinates.
  • (2) [x,y]=pol2cart(th,r) is to convert polar coordinates into rectangular coordinates.

2.2 Recursive call of function

  • In MATLAB, functions can be nested, that is, a function can call other functions, or even call itself. When a function calls itself it is called a recursive call of the function.
  • For example, we take advantage of the recursive call of the function to find n ! n!n!
  • n ! n! n ! itself is defined recursively: n ! = { 1 , n ≤ 1 n ( n − 1 ) ! , n > 1 n!=\left\{\begin{matrix}1, n≤1 \\ n(n-1)!, n>1 \end{matrix}\right.n!={ 1n1n(n1)!n1
  • Obviously, finding n ! n!n ! needs to ask for( n − 1 ) ! (n-1)!(n1 )! , then recursive calls can be used. The function file factor.m that uses recursive calls is as follows:
function f=factor(n)
if n<1
    f=1;
else
    f=factor(n-1)*n;  %递归调用求(n-1)!
end
  • Call the function file factor.m in the script file, find s = 1 ! + 2 ! + 3 ! + 4 ! + 5 ! s=1!+2!+3!+4!+5!s=1!+2!+3!+4!+5!
s=0;
n=input('n= ');
for i=1:n
    s=s+factor(i);
end
disp(['从1到',num2str(n),'的阶乘和为:', num2str(s)])
  • Run the script file in the command line window:
n= 515的阶乘和为:153
  • Arbitrary order of questions. The function randperm(n) provided by MATLAB can generate an arbitrary permutation from integer 1 to integer n. Write a function to implement the function of the randperm(n) function, that is, given a row vector composed of arbitrary numbers, and then generate any permutation of the elements of the row vector.
  • Consider writing two different functions that do exactly the same thing but differ in their control structures. The first function uses a loop structure, which can be controlled by a for statement or a while statement, and the second function uses recursive calls.
  • (1) The function uses a loop structure.
function Y=rndprm1(X)
%RNDPRM1 用for循环产生一个行向量的任意排列
%rndprm1(X)产生行向量X的任意排列
[m,n]=size(X);
if m>1
    error('RNDPRM1 accepts as inputs only vectors');
end
Y=[];  %从一个空矩阵开始
l=n;  %X的元素个数
for i=1:n
    k=1+fix(1*rand);    %随机选择Y的下一个元素的位置
    x=X(k);  %被选择的元素
    Y=[Y,x];  %将x添加到Y中
    X(k)=[];  %从X中删除x
    l=l-1;  %更新X的元素个数
end
  • (2) The function is called recursively.
function Y=rndprm2(X)
%RNDPRM2 用for循环产生一个行向量的任意排列
%rndprm2(X)产生行向量X的任意排列
[m,n]=size(X);
l=n;
if m>1
    error('RNDPRM2 accepts as inputs only vectors');
end
if n<=1
    Y=X;
else
    k=1+fix(1*rand);    %随机选择Y的下一个元素的位置
    x=X(k);  %被选择的元素
    X(k)=[];  %从X中删除x
    Z=rndprm2(X);  %将剩下的元素随机排列
    Y=[Z,x];  %构造输出向量
    l=l-1;  %更新X的元素个数
end
  • (3) Call the defined function in the command line window, the command is as follows:
>> rndprm1([34,6,3,54,2,5,454])

ans =

    34     6     3    54     2     5   454

>> rndprm2([34,6,3,54,2,5,454])

ans =

   454     5     2    54     3     6    34

  • Because MATLAB treats a string of length n as a vector of length n, you can also use strings as arguments to functions. For example:
>> rndprm1('apple')

ans =

    'apple'

>> rndprm2('apple')

ans =

    'elppa'

2.3 Adjustability of function parameters

  • MATLAB has a feature in function calls, that is, the number of parameters passed by the function can be adjusted. With this, one function can perform multiple functions.
  • When calling a function, MATLAB uses two predefined variables nargin and nargout to record the number of input actual parameters and output actual parameters when calling the function respectively. As long as these two variables are included in the function file, the number of input/output parameters when the function file is called can be accurately known, so as to determine how the function is processed.
  • Example of nargin usage.
  • Create the function file charray.m.
function fout=charray(a,b,c)
if nargin==1
    fout=a;
elseif nargin==2
    fout=a+b;
elseif nargin==3
    fout=(a*b*c)/2;
end
  • Create the script file mydemo.m.
a=1:3;
b=a';
x=charray(a);
y=charray(a,b');
z=charray(a,b,3);
disp(['x=    ',num2str(x)])
disp(['y=    ',num2str(y)])
disp(['z=    ',num2str(z)])
  • The output after executing the script file mydemo.m is as follows:
x=    1  2  3
y=    2  4  6
z=    21
  • In the script file mydemo.m, the function file charray.m is called three times, because the input parameters are 1, 2, and 3 respectively, so different operations are performed and different function values ​​are returned.

2.4 Global variables and local variables

  • In MATLAB, variables in a function file are local and isolated from other function files and the MATLAB workspace, that is, variables defined in one function file cannot be referenced by another function file.
  • If a variable is defined as a global variable in several functions, then these functions will share this variable. The scope of a global variable is the entire MATLAB workspace, that is, it is valid throughout, and all functions can access and modify it. Therefore, defining a global variable is a means of transferring information between functions.
  • Global variables are defined with the global command, and the format is as follows:
    global变量名
  • Example of global variable application.
  • First create the function file wadd.m, which adds weighted parameters to the input.
function f=wadd(x,y)
global ALPHA BETA
f=ALPHA*x+BETA*y;
  • Enter commands in the command line window and get output results.
>> global ALPHA BETA
>> ALPHA=1;
>> BETA=2;
>> s=wadd(1,2)

s =

     5

  • Since the two variables ALPHA and BETA are defined as global variables in the function wadd and the basic workspace, as long as the values ​​of ALPHA and BETA are changed in the command line window, the weights of x and y in the function can be changed without Modify the wadd.m file.
  • In actual program design, global variables can be defined in all functions that need to call global variables, so that data sharing can be realized. In the function file, the definition statement of the global variable should be placed before the use of the variable. In order to facilitate the understanding of all global variables, the definition statement of the global variable is generally placed at the front of the file. In order to use global variables in the workspace, global variables must also be defined.
  • It is worth pointing out that in programming, global variables can certainly bring some convenience, but it destroys the encapsulation of variables by functions and reduces the readability of programs. Therefore, in structured programming, global variables are Unpopular, especially when the program is large and there are many subroutines, global variables will bring inconvenience to program debugging and maintenance, so the use of global variables is not recommended. If you must use a global variable, it is best to give it a name that can reflect the meaning of the variable, so as not to be confused with other variables.

Second, the special form of the function

  • In addition to the most commonly used definition of a function through a function file, MATLAB can also use subfunctions, and can also customize functions through inline functions and anonymous functions.

1. Subfunction

  • In the function definition of MATLAB, if the function is long, it is often possible to write multiple functions in different function files, but sometimes the function may be very short, and you may want to put multiple function definitions in the same function file. There is a problem with the definition of sub-functions.
  • In MATLAB, multiple functions can be defined in a function file at the same time. The first function that appears in the function file is called the primary function (Primary Function), and other functions are called subfunctions (Subfunction), but it should be noted that Subfunctions can only be called by functions in the same function file.
  • When saving a function file, the name of the function file is generally the same as the name of the main function, and the external program can only call the main function. For example, to create func.m file, the procedure is as follows.
function d=func(a,b,c)  %主函数
d=subfunc(a,b)+c;
function c=subfunc(a,b)  %子函数,此c非彼c,这里的c是形式输出变量
c=a*b;
  • Call the main function in the command line window, the result is as follows:
>> func(3,4,5)

ans =

    17

  • Note that the work areas of the main function and sub-functions in the same function file are independent of each other, and the information transfer between functions can be realized through input and output parameters and global variables.

2. Inline functions

  • A function expression in the form of a string can be converted into an inline function by inlinethe function . For example a='(x+y)^2', the inline function f(x,y)=(x+y)^2 can be generated by f=inline(a).
>> a='(x+y)^2';
>> f=inline(a)

f =

     内联函数:
     f(x,y) = (x+y)^2

>> f(3,4)

ans =

    49

3. Anonymous functions

  • The basic format of an anonymous function is as follows:
    函数句柄变量=@ (匿名函数输入参数)匿名函数表达式
  • Among them, the function handle variable is equivalent to the alias of the function, which can be used to call the function indirectly; "@" is an operator for creating a function handle; "@" defines an anonymous function, including function input parameters and function expressions; the function has When multiple input parameters are entered, the parameters are separated by commas. For example:
>> sqr=@(x) x.^2  %定义匿名函数

sqr =

  包含以下值的 function_handle:

    @(x)x.^2

>> sqr([1,2,3])  %调用匿名函数

ans =

     1     4     9

>> f=@(x,y) x^2+y^2;
>> f(3,4)

ans =

    25

  • You can also use the following statement to define a function handle for an existing function, and use the function handle to call the function.
    函数句柄变量=@函数名
  • Among them, the function name can be an internal function provided by MATLAB, or a user-defined function file. For example:
>> h=@sin  %8取正弦函数句柄

h =

  包含以下值的 function_handle:

    @sin

>> h(pi/2) %通过函数句柄变量h来调用正弦函数

ans =

     1

  • The execution efficiency of anonymous functions is significantly higher than that of inline functions, and it is also more convenient and efficient than inline functions in terms of parameter passing. Inline functions will be deleted in future MATLAB versions and replaced by anonymous functions. What inline functions can achieve, anonymous functions can be implemented better, and the calling efficiency is much higher than that of inline functions.

3. Program debugging and optimization

  • Program debugging (Debug) is an important part of program design. MATLAB provides the corresponding program debugging function, which can not only debug the program through the MATLAB editor, but also combine specific commands in the command line window.
  • There are many ideas of program design. Different programs can be designed for the same problem, and the execution efficiency of different programs will be very different, especially when the data scale is large, the difference is particularly obvious. Therefore, sometimes it is necessary to Analyze the execution efficiency of the program with the help of performance analysis tools, and make full use of the characteristics of MATLAB to optimize the program, so as to achieve the purpose of improving program performance.

1. Program debugging method

  • Generally speaking, there are two types of application errors, one is syntax errors, and the other is runtime errors. MATLAB can check out most of the grammatical errors, give the corresponding error message, and mark the line number of the error in the program. Errors during program operation refer to errors in the running results of the program, and such errors are also called program logic errors.
  • The MATLAB system is powerless to logic errors and will not give any prompt information. At this time, some debugging methods can be used to find logic errors in the program.

1.1 Use the debug function to test the program

  • MATLAB provides a series of program debugging functions for breakpoint operation and execution control during program execution. Entering the following command in the MATLAB Command Window will output a summary of the debug function and its purpose.
>> help debug
  • Commonly used debugging functions are as follows.
  • (1) dbstop: Set a breakpoint at an appropriate position in the program, so that the system stops executing before the breakpoint, and the user can check the value of each variable to judge the execution of the program and help find errors. Use the following commands to display common formats for dbstopfunctions .
>> help dbstop
  • (2) dbclear: Clear the breakpoint set with dbstopthe function .
  • (3) dbcont: Resume the execution of the program from the breakpoint until another breakpoint or error of the program is encountered.
  • (4) dbstep: Execute one or more lines of statements, and return to the debug mode after execution. If a breakpoint is encountered during execution, the program will stop.
  • (5) dbquit: Exit the debug mode and return to the basic workspace, all breakpoints are still valid.

1.2 Debugging with debugging tools

  • When creating a new M file or opening an M file in the MATLAB editor, the editor tab provides a breakpoint command group. By setting a breakpoint on the M file, the program can run to a certain line and pause. At this time, you can view and modify the work variables in the area.
  • Click the breakpoint command button, and a drop-down menu will pop up, in which there are 6 commands, which are used to clear all breakpoints, set/clear breakpoints, enable/disable breakpoints, set or modify conditional breakpoints (conditional breakpoints can make the program Execution stops when certain conditions are met), stops when an error occurs (excluding errors in the try...catch statement), and stops when a warning occurs.
  • Set a breakpoint in the M file and run the program, the program enters the debug mode and runs to the first breakpoint, at this time, the debug command group appears on the editor tab, and the prompt in the command line window changes to K> >.
  • After entering the debug mode, it is best to lock the editor window, that is, dock to the MATLAB main window, so as to observe the changes of variables during the code running. To exit debug mode, click the Exit Debug button in the Debug Commands group.
  • There are 4 commands to control single-step operation. Some command buttons are not activated until the program is run. These command buttons are activated only when a breakpoint is set in the program and the program stops at the first breakpoint. The functions of these command buttons are as follows.
  • (1) Step: single-step operation. With each click, the program runs a statement, but does not step into a function.
  • (2) Step into: single-step operation. When a function is encountered, it enters the function and still runs in a single step.
  • (3) Step out: Stop single-step operation. If it is in the function, jump out of the function; if it is not in the function, run directly to the next breakpoint.
  • (4) Run to the cursor: directly run to the cursor position.

2. Program performance analysis and optimization

2.1 Program performance analysis

  • Using the profiler (Profiler), tic function and toc function can analyze the time consumption of each link of the program, and the analysis report can help users find the bottleneck that affects the running speed of the program, so as to optimize the code.
  • The profiler uses a graphical interface to allow users to deeply understand the time spent by each function and each statement in the function during program execution, so as to improve the program in a targeted manner and improve the operating efficiency of the program.
  • Suppose there is a script file testp.m:
x=-20:0.1:20;
y=300*sin(x)./x;
plot(x,y);
  • Enter the following command in the command line window of MATLAB:
>> profile on
>> testp
>> profile viewer
  • At this point, MATLAB opens a profiler window, displaying the analysis results. The probing summary table provides the time of running the file and the calling frequency of related functions, reflecting that the entire program takes 2.626s, and the newplot function called in drawing graphics takes the most time. Click a function name to open the detailed report of the corresponding function.

insert image description here

2.2 Program optimization

  • MATLAB is an interpreted language with slow calculation speed, so how to improve the running speed of the program is an important consideration when designing the program. The following methods are available for optimizing program operation.
  • (1) Use vectorized operations. In actual MATLAB programming, in order to improve the execution speed of the program, vector or matrix operations are often used instead of loop operations. First generate a vector iii,for aftermathiii generates vectorfff f f Each element value of f corresponds toyyEach accumulative item of y , and then use sumthe functionThe procedure is as follows:
n=100;
i=1:n;
f=1./(i.*i);
y=sum(f)
  • If the value of n in the program is changed from 100 to 100000, and the two programs are run separately, it can be clearly seen that the program written by the vector calculation method is much faster than the loop program.
  • (2) Pre-allocate memory space. The processing speed of a for loop can be improved by preallocating the memory space for the vector or array before the loop. For example, the following code uses the function zerosto pre allocate the memory space of the vector a used in the for loop, so that the running speed of this for loop is significantly accelerated.
  • Procedure 1:
clear;
a=0;
for n=2:1000
    a(n)=a(n-1)+10;
end
  • Procedure 2:
clear;
a=zeros(1,1000);
for n=2:1000
    a(n)=a(n-1)+10;
end
  • Program 2 uses the method of pre-defined matrices, and the running time is shorter than Program 1.
  • (3) Reduce the computational intensity. When implementing related calculations, try to use operations with a smaller amount of calculations, so as to improve the calculation speed. In general, multiplication is faster than exponentiation, and addition is faster than multiplication. For example:
clear;
a=rand(32);  %生成一个32×32矩阵
x=a.^3;
y=a.*a.*a;
  • From Profiler's evaluation report, it can be seen that a.*a.*a takes much less time than a.^3 operation.

Guess you like

Origin blog.csdn.net/weixin_45891612/article/details/130635489