如何调用' Matlab的功能来自另一个脚本

时间:2015-07-27 15:40:31

标签: matlab

我的Matlab脚本.m文件太大了。 我想将功能移动到多个.m文件,将我的移动功能从主文件移动到其他几个.m文件,每个文件都基于功能类别。

主.m文件如何调用'这些其他新的.m文件中的函数?

1 个答案:

答案 0 :(得分:9)

我的回答中提供的所有信息都可以在Function Basics MATHWORKS 中找到。

如何在MATLAB中创建一个函数?您使用以下模板。此外,函数的名称和文件的名称应该类似。

% ------------------- newFunc.m--------------------
function [out1,out2] = newFunc(in1,in2)
out1 = in1 + in2;
out2 = in1 - in2;
end
%--------------------------------------------------

要使用多个功能,您可以将它们应用于单独的m-file或使用nested/local结构:

单独的m文件:

在此结构中,您将每个函数放在一个单独的文件中,然后在主文件中按名称调用它们:

%--------- main.m ----------------
% considering that you have written two functions calling `func1.m` and `func2.m`
[y1] = func1(x1,x2);
[y2] = func2(x1,y1);
% -------------------------------

本地功能:

在此结构中,您只有一个m文件,在此文件中您可以定义多个函数,例如:

% ------ main.m----------------
    function [y]=main(x)
    disp('call the local function');
    y=local1(x)
    end

    function [y1]=local1(x1)
    y1=x1*2;
    end
%---------------------------------------

嵌套函数:

在此结构中,函数可以包含在另一个函数中,例如:

%------------------ parent.m -------------------
function parent
disp('This is the parent function')
nestedfx

   function nestedfx
      disp('This is the nested function')
   end

end
% -------------------------------------------

您无法从m文件外部调用嵌套函数。为此,您必须为每个函数使用单独的m文件,或使用类结构。

相关问题