如何从另一个脚本中“调用" Matlab函数 [英] How to 'call' Matlab functions from another script

查看:818
本文介绍了如何从另一个脚本中“调用" Matlab函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My Matlab script .m file is getting too big. I want to move functionality to multiple .m files my moving functions from the primary file to a several other .m files, each based on category of functionality.

主.m文件如何在其他新的.m文件中调用"功能?

How can the primary .m file 'call' functions in these other new .m files?

推荐答案

我的答案中提供的所有信息都可以在

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-files 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.

这篇关于如何从另一个脚本中“调用" Matlab函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆