更新时间:2022-06-20 01:14:31
All the information provided in my answer can be found in Function Basics at MATHWORKS.
如何在MATLAB中制作函数?您使用以下模板.此外,函数的名称和文件的名称应该相似.
How to make a function in MATLAB? You use the following template. In addition the name of the function and the name of the file should be similar.
% ------------------- newFunc.m--------------------
function [out1,out2] = newFunc(in1,in2)
out1 = in1 + in2;
out2 = in1 - in2;
end
%--------------------------------------------------
要使用多种功能,您可以将其应用于单独的m-file
或使用nested/local
结构:
For using multiple functions you can apply them either in separate m-file
s or using nested/local
structures:
单独的m文件:
在这种结构中,您将每个函数放在一个单独的文件中,然后通过它们的名称在主文件中调用它们:
In this structure you put each function in a separate file and then you call them in the main file by their names:
%--------- main.m ----------------
% considering that you have written two functions calling `func1.m` and `func2.m`
[y1] = func1(x1,x2);
[y2] = func2(x1,y1);
% -------------------------------
本地功能:
在此结构中,您只有一个m文件,在此文件中,您可以定义多个功能,例如:
In this structure you have a single m-file and inside this file you can define multiple functions, such as:
% ------ main.m----------------
function [y]=main(x)
disp('call the local function');
y=local1(x)
end
function [y1]=local1(x1)
y1=x1*2;
end
%---------------------------------------
嵌套功能:
在此结构中,函数可以包含在另一个函数中,例如:
In this structure functions can be contained in another function, such as:
%------------------ parent.m -------------------
function parent
disp('This is the parent function')
nestedfx
function nestedfx
disp('This is the nested function')
end
end
% -------------------------------------------
您不能从m文件外部调用嵌套函数.为此,您必须为每个函数使用单独的m文件或使用类结构.
You cannot call nested function from outside of the m-files. To do so you have to use either separate m-files for each function, or using class structure.