当前位置:网站首页>Matlab (4) functions and files
Matlab (4) functions and files
2022-07-19 12:13:00 【Kaizhi~】
Catalog
function
Definition
MATLAB The definition of the function in is as follows :
function Output parameters = Function name ( Input parameters )
The body of the function
end
% Output parameter format
% 1. nothing (function Function name ( Input parameters ))
% 1. Single variable (function y = Function name ( Input parameters ))
% 2. Array form (function [y1,y2,……] = Function name ( Input parameters ))
% Input parameter format
% 1. nothing (function Output parameters = Function name ())
% 1. Single variable (function Output parameters = Function name (x))
% 2. Array form (function Output parameters = Function name (x1,x2,……))
In some places, you can define functions without end, But some must be added , Therefore, it is suggested to add end.
Taking array form as input parameter or function parameter is actually a single variable , It's just MATLAB The single variable of is also an array , Therefore, there is no need to worry about how to assign values if the output parameter is an array .
classification
From the perspective of being called , Functions are divided into main functions and sub functions , The main function refers to the top in the file , Function with the same name as the file name ,( Be careful : The two conditions are actually fixed , Function file The first line in must be the function definition with the same name as the file name ) stay MATLAB in , Only the main function can be called by other files .( in other words Call a function in a function file , Can and can only call the main function , And the main function name is the same as the file name )
From the perspective of particularity , Functions can be divided into four kinds : Nested function 、 Anonymous functions 、 Private functions and overloaded functions .
Nested function
Definition : Functions defined within functions .
effect : It doesn't seem to work .
Nested functions can manipulate variables in parent functions .( Here assume that the former is called the parent function )
Anonymous functions
The format of anonymous function is as follows :
Function name = @( Variable 1, Variable 2,……) expression
Be similar to C In language #define Function name ( Variable 1, Variable 2,……) expression , That is, through the function name and the corresponding variables , Return the value of the corresponding expression .
Command line windows are not allowed function Create a function , But anonymous functions are allowed .( At least 2020 The version is like this )

Anonymous functions seem to be also called handle functions , But it is a little different from the function handle ( Pay attention to handle functions and function handles ), Function handle refers to , Assign an existing function to another name , To complete the call of an existing function by another name , similar #define New name Existing function name ,MATLAB The method of implementing function handle is as follows :
% function BubbleSort
function y = BubbleSort(x)
len = length(x);
for m = 1 : len - 1
for n = 1 : len - m
if (x(n) > x(n + 1))
[x(n), x(n + 1)] = deal(x(n+1), x(n));
end
end
disp(['Sort step', num2str(m), ': ', num2str(x)])
end
y=x
end
% Define the function above
fun = @BubbleSort
% here , Can pass fun Call function BubbleSort
x=[6,3,7,8,5,1,2,4,9] % Define an array
y = fun(x) % Equivalent to y = BubbleSort(x)
Private functions
Private functions , That is, functions with access restrictions , The function file of the private function is located in private In the folder , As shown in the figure below x.m Functions are private functions , Private functions can only be called by files in the parent folder , The following is an example ,x.m Can only be y.m、Base.m A file called , Even if it is added to the file path , Can't be z.m、nua.m Wait for file call .

MATLAB For function access, please refer to MATLAB File path .
overloaded function
overloaded function , stay MATLAB Middle refers to the same function name , But functions with different parameter types or numbers . Of course, there cannot be files of the same type with the same name in the same directory , Therefore, overloaded functions are generally located in different file directories .
The definition of overloaded function is exactly the same as that of ordinary function , When called ,MATLAB The corresponding function will be called according to the parameter type .
file
file type
MATLAB The files in can be divided into 3 Kind of , namely .m file ,.fig file ,.mat file .
.m file
MATLAB Medium .m The document is similar to C In language .c file , It is used for storing MATLAB Code . Although the command line can also be executed , But it cannot be saved effectively , And if you are not careful, you will output a lot of information , Disrupt the formation .
.m Files can be divided into script files and function files , The code in the script file can be executed in sequence ( That is, lines of code ), In function files, keywords are used function start , Generally, input and output parameters are required , Therefore, even if you click Run, an error will be reported .( If it is a function without input parameters , Even if there is a return value , It can also run successfully )
Of course, there is actually no distinction between script files and function files , similar C Language , Has been main Function execution , Call other .c Functions in the file ,MATLAB Also the same , Always execute in the script file , It just calls the functions in the function file .
stay MATLAB In the current folder window of the, you can find that the icons in front of the script file and the function file are different , As shown in the figure below , above BubbleSort.m For function file , Below TestBubbleSort.m The file is a script file .

The following are the specific contents of the two documents , If opened BubbleSort.m File and click Run , The missing parameter... Will be displayed in the command line window , And open TestBubbleSort.m File and click Run , At this time, output after sorting normally .
( When running, it should be under the corresponding path , At this time, the corresponding file should be visible in the current folder window )
% BubbleSort.m file ( Function file )
function y = BubbleSort(x)
len = length(x);
for m = 1 : len - 1
for n = 1 : len - m
if (x(n) > x(n + 1))
[x(n), x(n + 1)] = deal(x(n+1), x(n));
end
end
disp(['Sort step', num2str(m), ': ', num2str(x)])
end
y=x
end
% TestBubbleSort.m( Script files )
clc; % Clear the command of the current command window
clear; % Clear memory
x = randperm(9); % take 1 To 9 These numbers are randomly scrambled and assigned to x
disp([' Data before sort: x = ', num2str(x)]);
disp('--------------------------------------');
y = BubbleSort(x); % Call the bubble sort function to x Sort , The result is y
disp('--------------------------------------');
disp([' Data before sort: y = ', num2str(y)]);
There can be multiple functions in the function file , And script files can also write functions , Of course, the functions written in the script file cannot be at the top of the file ( I can't use function As the beginning of the file ), When the script file calls a function , and a When the function is defined in this script file , Priority should be given to a Function instead of a function .( decision .m Files are for code , According to the classification of so-called scripts and functions that are only available in code )
Click the run button ,MATLAB Which script file to run depends on which file is currently open in the editor window , If you open a script file , Then execute the script file , If it is a function file , It will be based on whether there are input parameters , Decide to report an error or run .
.fig file
MATLAB Medium .fig File is the user interface window definition file , It is used to define UI Interface file , adopt MATLAB After opening this type of file, the corresponding UI Interface , Operate at this time ( For example, click the button with the mouse ) The corresponding callback function will be called .
.fig The creation of the file can be entered in the command line window guide, The following pop-up window pops up , Select the corresponding template and modify the path and file name , Then click OK to generate .

here MATLAB The interface is shown in the figure below , You can see , Two files appear in the current folder window ,try.fig The document is UI Interface definition file ,try.m The corresponding callback function is stored in the file , For example, in UI Place a button in the interface , Then click , The code to be executed will be placed in try.m In the corresponding callback function in the file .
About .fig file , Yes UI The use of the interface will be written in other articles .( When you see this sentence , It means I haven't finished writing )

.mat file
.mat File is MATLAB File used to save data in , adopt save Functions and load Function can be completed .mat Operation of file , Store data in .mat file , And from .mat Export data from file , The example and explanation of the function are shown in the following table .
| Function name | Example | explain |
|---|---|---|
| save | save file name save file name Variable 1 name Variable 2 name | Save the variables of the workspace to the corresponding file ( Generate corresponding .mat file ) The variables in the workspace 1 And variables 2 Save to the appropriate file |
| load | load file name load file name Variable 1 name Variable 2 name | Transfer the corresponding file (.mat) The variables in the file are loaded into the workspace Transfer the corresponding file (.mat) Variables in the file 1 And variables 2 Load into workspace |
debugging
MATLAB Enter the method of debugging , It seems that you can only set the breakpoint and click Run , Then start the corresponding debugging button , As shown in the figure below , Click... Next to the serial number in the editor window “-” To set breakpoints , When I hit run , Various debugging icons appear on the editor tab in the toolbar .

Name of each icon 、 Shortcut key 、 The name is as follows .
Section commissioning
There is no corresponding icon for section debugging , By entering two percent signs “%%” Segment the code , here Ctrl+Enter You can simply run the contents of this section .( from %% To another %%, Click the corresponding section , The section highlights , The following figure 7~10 That's ok )
The addition and operation of sections can also be used without debugging , Move the mouse to the corresponding line , Right click and select “ Execute the current section (E)” or “ Insert section (I)”. Through section debugging, you can debug a piece of code alone .( Of course, you may want to pay attention to the variables used in this section , And it seems that private functions cannot be used )

Step by step debugging
After debugging through breakpoints , You can perform one-step debugging , Single step debugging can pass surface Buttons in ( Or by shortcut keys ) Run the code line by line , See the effect .
边栏推荐
- Three. JS basic element usage
- Research on Wenhua commodity index
- zabbix-snmp监控
- js链式调用sleep函数 ------- <秋招打卡篇二>
- Leetcode 20. 有效的括号
- 对Rapidly-exploring Random Trees(RRT)路径规划方法的理解
- Tidb memory control document
- 2022年了,跨端技术方案应该怎么选?
- Familiar with nestjs (beginner)
- [original] magisk+shamiko has been tested by app root
猜你喜欢

LeetCode_17_电话号码的字母组合

MySQL learning notes - constraints

Nature | the carbon sequestration rate of groundwater is similar to that of oligotrophic marine system

Kunlunbase online meetup is waiting for you~

The underlying principle of file operation (inode and hard and soft links, time attributes of files)

Lychee sound quality high fidelity AI noise reduction technology sharing

01背包面试题系列(一)

数字化转型的两种误区

字符串相关函数(二)

windows10:vscode下go语言的适配
随机推荐
STL string input / output overload
Introduction and Simulation Implementation of string class
Why does the magnetic variable speed gear reverse?
LeetCode_ 17_ Letter combination of telephone number
ZABBIX SNMP monitoring
Nintendo patent shows that the follow-up products of fitness ring accessories may be under development
Time consuming test of construction and sorting of set, vector and list
HCIP(4)
HCIP (7)
HarmonyoS快速入门:Hello world
2022年低压电工考试题及在线模拟考试
Gradient button function button drawing C language example
Redis Distributed cache - Redis Cluster
3. Golang string type
SQL盲注详解
How to build dashboard and knowledge base in double chain note taking software? Take the embedded widget library notionpet as an example
The adaptation of go language under windows10:vscode
Enabling cities to "plan, build, operate, manage and serve" -- MAPGIS CIM platform explores "cim+" multi scenario applications
LeetCode_ 77_ combination
Conversion between Swift binary data and hexadecimal string