MATLAB 与命名空间最接近的是什么? [英] What is the closest thing MATLAB has to namespaces?

查看:17
本文介绍了MATLAB 与命名空间最接近的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实验室中有很多 MATLAB 代码.问题是真的没有办法组织它.由于所有函数都必须在同一个文件夹中才能被调用(或者您必须将一堆文件夹添加到 MATLAB 的 path 环境变量中),看来我们注定要在其中加载大量文件同一个文件夹,都在全局命名空间中.有没有更好的方法来组织我们的文件和函数?我真希望有某种模块系统...

We have a lot of MATLAB code in my lab. The problem is there's really no way to organize it. Since all the functions have to be in the same folder to be called (or you have to add a bunch of folders to MATLAB's path environment variable), it seems that we're doomed have loads of files in the same folder, all in the global namespace. Is there a better way to organize our files and functions? I really wish there were some sort of module system...

推荐答案

MATLAB 有一个包的概念,它可以嵌套并包含类和函数.

MATLAB has a notion of packages which can be nested and include both classes and functions.

只需在路径的某处创建一个目录,并以 + 作为第一个字符,例如 +mypkg.然后,如果该目录中有一个类或函数,它可能被称为 mypkg.mything.您还可以使用 import mypkg.mysubpkg.* 从包中导入.

Just make a directory somewhere on your path with a + as the first character, like +mypkg. Then, if there is a class or function in that directory, it may be referred to as mypkg.mything. You can also import from a package using import mypkg.mysubpkg.*.

将一堆函数移动到一个包中的一个主要问题是函数和类不会自动导入它们所在的包.这意味着,如果您在不同的 m 文件中有一堆函数相互调用,您可能需要花费一些时间将 import 放入或限定函数调用中.不要忘记将导入也放入调用的子函数中.更多信息:

The one main gotcha about moving a bunch of functions into a package is that functions and classes do not automatically import the package they live in. This means that if you have a bunch of functions in different m-files that call each other, you may have to spend a while dropping imports in or qualifying function calls. Don't forget to put imports into subfunctions that call out as well. More info:

http://www.mathworks.com/help/matlab/matlab_oop/scoping-classes-with-packages.html

这篇关于MATLAB 与命名空间最接近的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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