matlab中的变量命名空间

variable namespace in matlab

最近我发现matlab代码在函数中调用assignin('caller',...)时在调用函数中创建新变量时,如果变量名与路径中的matlab函数名相同。

这里有一个简单的代码片段来演示这个问题。

function myfunctest
  sin = 0;   
  subfcn_set; % call subfcn_set to make a new variable
  whos % list variables in current workspace
  sin % raise error because it calls the sin function
end

function subfcn_set
  assignin('caller', 'sin', 'I am sine');
end

将代码片段保存到 myfunctest.m 并 运行 在 matlab 中

>> myfunctest
  Name      Size            Bytes  Class    Attributes    
  sin       1x9                18  char     

sin =    
I am sine

一切看起来都很好。但是,如果我删除 myfunctest 中的 sin = 0 并再次删除 运行,

>> myfunctest
  Name      Size            Bytes  Class    Attributes    
  sin       1x9                18  char     
Error using sin
Not enough input arguments.    
Error in myfunctest (line 8)
sin

即使变量 sin 存在,如 whos 所示,内置函数 sin 也会被调用。这也适用于路径中的其他 matlab 函数名称。

如果我们将变量名从 sin 更改为其他名称,例如 notafunc,无论初始化如何,一切看起来都很好。

>> myfunctest
  Name          Size            Bytes  Class    Attributes    
  notafunc      1x13               26  char   
notafunc =    
I am notafunc

这实际上不是"problem"。来自 assignin 的文档:

assignin(ws, 'var', val) assigns the value val to the variable var in the workspace ws. The var input must be the array name only; it cannot contain array indices. If var does not exist in the specified workspace, assignin creates it.

因为命名空间中存在一个函数sin(),所以 matlab 不会创建变量。

除此之外,我不推荐这种方法,因为它会使使用您的代码的其他人感到困惑。如果您不知道这条线的存在,您将不会意识到会发生什么。如果子函数与使用子函数的函数在同一个 .m 文件中定义,则子函数可以作为其他函数的例外。但是,即使如此,它也应该稀疏地使用以防文件很大。