有没有办法调用 MATLAB“子函数”?从文件外部?
为了在 MATLAB 中定义一个(非匿名)函数,您需要创建一个与该函数同名的文件;例如,可以在文件 myfunc.m 中定义一个名为 myfunc 的函数,如下所示:
function rtn = myfunc(arg)
% do some stuff
end
假设在同一个文件 myfunc.m 中,我有也是一个子函数,据
function rtn = myfunc(arg)
% do some stuff
end
function rtn = mysubfunc(arg)
% do some other stuff
end
我所知,没有办法从 subfunc.m 文件之外的任何地方执行访问 mysubfunc 。我一直并且继续对 MATLAB (R2010b) 中的这个小特性感到恼火。我错了吗?有任何方式从myfunc.m外部调用mysubfunc吗?
更新:新问题:有什么好的方法可以做到这一点吗?或者我真的应该忍耐并继续制作更多文件吗?
Possible Duplicate:
Is it possible to define more than one function per file in MATLAB?
In order to define a (not anonymous) function in MATLAB, you need to create a file with the same name as the function; e.g., a function called myfunc can be defined in a file myfunc.m as per:
function rtn = myfunc(arg)
% do some stuff
end
Suppose in this same file myfunc.m, I have also a sub-function, as in
function rtn = myfunc(arg)
% do some stuff
end
function rtn = mysubfunc(arg)
% do some other stuff
end
AFAIK, there is no way to access mysubfunc from execution happening anywhere outside of the subfunc.m file. I have been and continue to be annoyed by this little idiosyncrasy in MATLAB (R2010b). Am I wrong -- is there any way to call mysubfunc from outside myfunc.m?
Update: New question: Is there any good way to do this? or should I really just suck it up and keep on making more files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将它们设置为实用程序类上的所有静态方法。这些函数可以通过名称进行全局引用,但您只需要管理一个 M 文件。
缺点是,您需要限定或导入对它们的所有引用,例如 mystuff.myfunc()。 “import mystuff.*”可以为类之外的代码处理这个问题。
在类内,函数之间的调用需要进行限定。 (恕我直言,Matlab 的 MCOS 语法中的大问题。)此外,它们比常规函数有更多的调用开销,因此如果您在紧密循环中调用它们,您的代码会更慢。从好的方面来说,现在它们是类成员,您可以重构它们以利用私有类字段和函数等。
如果您想组织代码库,可以将它们放在名称空间中,方法是将它们放在名称以“+”开头的目录中。文件数量相同,但至少您的目录有一些结构。
You could make them all static methods on a utility class. The functions will be globally referenceable by name, but you only need to manage one M-file.
On the downside, you'll need to qualify or import all references to them, like mystuff.myfunc(). An "import mystuff.*" can take care of this for code outside of the class.
Within the class, calls between the functions will need to be qualified. (Big wart in Matlab's MCOS syntax, IMHO.) Also, they'll have more calling overhead than regular functions, so your code will be slower if you're calling them in tight loops. On the upside, now they're class members, and you can refactor them to make use of private class fields and functions and so on.
If you want to organize your codebase, you can stick them in a namespace by putting them in a directory whose name starts with a "+". Same number of files, but at least you have some structure to your dirs.
通过函数句柄访问。它可以看作是 OO 模拟(静态方法)。不过,我不建议您使用此技术。
Accessing through function handles. It can be seen as OO emulation (static methods). I do not recommend you to use this technique though.