eval('expression')在MATLAB代码中的用法和含义? [英] Use and implications of eval('expression') in MATLAB code?

查看:484
本文介绍了eval('expression')在MATLAB代码中的用法和含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在matlab的其他人的代码中遇到了使用功能 eval(expression)的情况: 例如:

I was encountered with usage of function eval(expression) in somebody else's code in matlab: for example:

for n = 1 : 4
sn = int2str( n) ;
eval( [ 'saveas( fig'  sn  ', [ sName' sn ' ], ''fig'' ) ' ] );
end

Matlab帮助中的MathWorks内容指出:

MathWorks stuff in Matlab Help pointed out that:

与其他MATLAB函数和语言构造相比,eval函数的许多常见用法效率较低,并且更难以读取和调试.

Many common uses of the eval function are less efficient and are more difficult to read and debug than other MATLAB functions and language constructs.

此后,我发现此功能在许多其他程序语言中的用法,例如Python,JavaScript,PHP.

After this, I find usage of this function in many other program languages, so as Python, JavaScript, PHP.

所以我有几个问题:

  1. 此功能的使用会影响我的代码的性能吗?
  2. 如果它会减慢执行速度,为什么会发生?
  3. 如果每次调用都会减慢执行速度,那么原则上使用此函数的原因是什么?

推荐答案

  1. 在这里使用eval肯定会比非eval版本慢,但很可能不会成为您代码中的瓶颈.但是,性能只是一个问题,维护(包括调试)和可读性是另一个问题.
  2. 之所以会出现速度下降,是因为Matlab使用JIT编译器,并且eval行无法优化.
  3. 大多数情况下,由于缺乏对Matlab功能的了解,因此通常都需要使用.在这种特殊情况下,问题在于图形句柄存储在名为fig1fig4的变量名称中.如果它们已存储在名为fig的数组中,即fig(1)等,则eval就不必要了.
  1. Using eval here will certainly be slower than a non-eval version, but most likely it won't be a bottleneck in you code. However, the performance is only one issue, maintenance (incl. debugging), as well as readability are other ones.
  2. The slowdown occurs because Matlab uses a JIT compiler, and eval lines cannot be optimized.
  3. Eval use is in most cases due to lack of knowledge about the Matlab functionality that would be appropriate instead. In this particular case, the issue is that the figure handles are stored in variable names called fig1 through fig4. If they had been stored in an array called fig, i.e. fig(1) etc, eval would have been unnecessary.

编辑这是洛伦·舒尔(Loren Shure)撰写的两篇出色的文章,介绍了为什么在Matlab中应避免使用eval的原因. 回避评估,和

EDIT Here are two excellent articles by Loren Shure about why eval should be avoided in Matlab. Evading eval, and More on eval.

这篇关于eval('expression')在MATLAB代码中的用法和含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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