在 MATLAB 中,我可以在同一个文件中包含脚本和函数定义吗? [英] In MATLAB, can I have a script and a function definition in the same file?

查看:50
本文介绍了在 MATLAB 中,我可以在同一个文件中包含脚本和函数定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数 f() 并且我想在 my_file.m 中使用它,这是一个脚本.

Suppose I have a function f() and I want to use it in my_file.m, which is a script.

  1. 是否可以在my_file.m中定义函数?
  2. 如果没有,假设我在 f.m 中定义了它.我如何在 my_file.m 中调用它?
  1. Is it possible to have the function defined in my_file.m?
  2. If not, suppose I have it defined in f.m. How do I call it in my_file.m?

我阅读了在线文档,但不清楚这样做的最佳方法是什么.

I read the online documentation, but it wasn't clear what is the best way to do this.

推荐答案

从 R2016b 版本开始,您可以拥有 脚本中的本地函数,如下所示:

As of release R2016b, you can have local functions in scripts, like so:

data = 1:10;            % A vector of data
squaredData = f(data);  % Invoke the local function

function y = f(x)
  y = x.^2;
end

在发布 R2016b 之前,唯一的函数类型 可以在 MATLAB 脚本中定义的是 匿名函数.例如:

Prior to release R2016b, the only type of function that could be defined inside a MATLAB script was an anonymous function. For example:

data = 1:10;            % A vector of data
f = @(x) x.^2;          % An anonymous function
squaredData = f(data);  % Invoke the anonymous function

请注意,匿名函数更适合简单操作,因为它们必须在单个表达式中定义.对于更复杂的函数,您必须在它们自己的文件中定义它们,将它们放置在 MATLAB 路径中的某个位置,使您的脚本可以访问它们,然后像​​调用任何其他函数一样从您的脚本中调用它们.

Note that anonymous functions are better suited to simple operations, since they have to be defined in a single expression. For more complicated functions, you will have to define them in their own files, place them somewhere on the MATLAB path to make them accessible to your script, and then call them from your script as you would any other function.

这篇关于在 MATLAB 中,我可以在同一个文件中包含脚本和函数定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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