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

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

问题描述

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


  1. 是否可以在 my_file.m 中定义函数?

  2. 如果没有,假设我在 fm 中定义了它。我如何在 my_file.m 中调用?

我在线阅读文件,但不清楚什么是最好的方法。

解决方案

从版本R2016b开始,您可以脚本中的本地功能,如下所示:

  data = 1:10; %#数据向量
squaredData = f(data); %#调用本地​​函数

函数y = f(x)
y = x。^ 2;
end

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

  data = 1:10; %#数据向量
f = @(x)x。^ 2; %#匿名函数
squaredData = f(data); %#调用匿名函数

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


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

  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.

解决方案

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

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

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天全站免登陆