Matlab中的作用域如何工作? [英] How does scoping in Matlab work?

查看:145
本文介绍了Matlab中的作用域如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是发现(令我惊讶)调用以下函数

I just discovered (to my surprise) that calling the following function

function foo()
if false
   fprintf = 1;
else
  % do nothing
end
fprintf('test')

给出错误Undefined function or variable "fprintf".我的结论是,变量的范围是在运行时确定的(在我对计算机语言尤其是Matlab的解释方式了解有限的情况下).谁能给我一些背景信息吗?

gives and error Undefined function or variable "fprintf". My conclusion is that the scope of variables is determined before runtime (in my limited understanding how interpretation of computer languages and specifically Matlab works). Can anyone give me some background information on this?

修改

我在上面忘记提及的另一件有趣的事情是

Another interesting thing I forgot to mention above is that

function foo()
if false
   fprintf = 1;
else
  % do nothing
end
clear('fprintf')
fprintf('test')

产生Reference to a cleared variable fprintf.

推荐答案

MATLAB在函数运行之前对其进行了解析.例如,它查找变量名,而不管激活(或不激活)那些变量的分支.也就是说,范围不是在运行时确定的.

MATLAB parses the function before it's ever run. It looks for variable names, for instance, regardless of the branching that activates (or doesn't activate) those variables. That is, scope is not determined at runtime.

附录:我不建议这样做,但是我看到很多人在用MATLAB做我不建议的事情.但是...考虑一下,如果有人定义了自己的称为"false"的函数会发生什么.运行前解析器不知道如果调用该函数会发生什么.

ADDENDUM: I wouldn't recommend doing this, but I've seen a lot of people doing things with MATLAB that I wouldn't recommend. But... consider what would happen if someone were to define their own function called "false". The pre-runtime parser couldn't know what would happen if that function were called.

这篇关于Matlab中的作用域如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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