本文介绍了如何在不创建多个文件的情况下将Matlab代码分解为函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数returnValue = someFunction(x,y)
returnValue = x * y + 3
end

然而,Matlab注意到I不允许在我的脚本中间简单地声明一个函数。我试着将函数移动到文件顶部,但是Matlab迫使我将函数重命名为文件名。



我很快意识到Matlab函数必须匹配他们的文件的名称。如何在单个文件中模块化我的Matlab代码?有没有一种方法可以在我的脚本中定义一个函数?

解决方案

匿名函数



对于非常小的函数,例如您的示例中的函数,您可以简单地定义一个匿名函数,如下所示: f = @(x,y )x * y + 3 。您甚至可以在您的工作区提示或任何脚本文件中定义这些功能。



嵌套函数

如果你将你的MATLAB脚本变成一个函数,它将允许你定义嵌套函数:

pre $ 函数a = my_script(x)
y = 3;
函数r = some_function(b)
r = b * y + 3;
end
a = some_function(x)
end

请注意,嵌套函数可以看到 y 的值。例如,当您优化ODE的参数并且您使用的求解器不提供修改参数值的方法时,这可能很方便。



子函数

您也可以在一个文件中定义一个具有多个本地子功能的函数。子功能定义在公共功能之下。在你的例子中 some_function 可以是 my_script.m 中的子函数。

 函数a = my_script(x)
y = 3;
p = 42;
a = some_function(x,y)+ p;
end

函数r = some_function(x,y)
r = x * y + 3;
end

end 关键字在这里是可选的。与嵌套函数相比,子函数对封装算法片段非常有帮助,因为 some_function 不会看到 p


I tried coding up a function in a Matlab .m file:

function returnValue = someFunction(x, y)
returnValue = x * y + 3
end

However, Matlab noted that I was not allowed to simply declare a function in the middle of my script. I tried moving the function to the top of the file, but Matlab forced me to rename my function to the name of the file.

I soon realized that Matlab functions must match the name of their files. How do I modularize my Matlab code within a single file? Is there a way I could just define a function in the middle of my script?

解决方案

Anonymous functions

For very small functions like the one in your example, you could simply define an anonymous function like this: f = @(x, y) x * y + 3. You can define such functions even in the prompt of your workspace or in any script file.

Nested functions

If you turn your MATLAB script into a function, it will allow you to define nested functions:

function a = my_script(x)
  y = 3; 
  function r = some_function(b)
    r = b * y + 3;
  end
  a = some_function(x)
end

Note that the nested function can see the value of y. This can be handy for example, when you optimize parameters of an ODE and the solver you use doesn't provide a means to modify parameter values.

Sub functions

You can also define a function with multiple local sub functions in one single file. Sub functions are defined below the "public" function. In your example some_function could be a sub function in my_script.m.

function a = my_script(x)
  y = 3;
  p = 42;
  a = some_function(x, y) + p;
end

function r = some_function(x, y)
  r = x * y + 3;
end

The end keywords are optional here. In contrast to nested functions, sub functions are rather helpful to encapsulate pieces of an algorithm, as some_function will not see the value of p.

这篇关于如何在不创建多个文件的情况下将Matlab代码分解为函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 13:47