4

使用 Matlab 的函数包实现命名空间

 3 years ago
source link: https://zhiqiang.org/coding/matlab-package-created-namespace.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在写 Matlab 程序时,函数的命名方式让人头疼,很难保证刚写的一个函数名在很久以前被用过,成为隐藏的一颗炸弹。

1. 使用方法

从 7.6 开始, Matlab 引入了函数包,可以将若干函数(以及类!)放到一个文件夹下,可实现命名空间的效果,如例:

+mypack
+mypack/pkfcn.m % a package function
+mypack/@myClass % class folder in a package

使用 help mypack 一次性列出mypack包下所有函数,这些函数可以通过以下方式引用:

z = mypack.pkfcn(a, b);
obj = mypack.myClass(arg1,arg2,...);

还可以建立多重包

+mypack/+pack2/fun.m

同样的方式引用:

z = mypack.pack2.fun(x, y);

函数包实现函数命名空间会增加函数调用的开销。验证方法是建立一个普通函数testadd

function s = testadd(a, b)
s = a + b;

同时将该函数复制到函数包+test 下。我可以使用下面三句语句检查运行效率:

tic; s = 0; for i = 1:1e6, s = s + i; end; toc; % 0.015344s
tic; s = 0; for i = 1:1e6, s = testadd(s, i); end; toc; % 0.556452s
tic; s = 0; for i = 1:1e6, s = test.testadd(s, i); end; toc; % 9.296256s

从第一条语句看,循环和计算加法所需的时间可忽略不计(百万次运行的量级上)。第二条语句的结论是 200 万次函数调用大约需 1 秒钟。第三条语句说明,同样的函数,若通过函数包调用,效率会降低到 10 万次调用就需要 1 秒钟。函数包的效率比普通函数慢 20 倍。

即使用下面这种方式预先申明函数也不行:

a = @test.testadd; 
tic; s = 0; for i = 1:1e6, s = a(s, i); end; toc; % 10.391726s

所以如果一个函数被调用多次(比如上百万次),最好还是别用函数包的形式,老老实实取一个不常见的函数名来避免函数名字冲突。

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK