【问题标题】:Access variable from other workspace in Matlab?从 Matlab 中的其他工作区访问变量?
【发布时间】:2012-01-24 05:21:51
【问题描述】:

是否有类似于assignin() 的东西来获取另一个工作空间中存在的变量并将其获取到本地工作空间,例如就像访问函数中的基础工作区变量一样!?

我目前正在尝试实现的一个示例是:我有一个函数bla(x),它接受一个参数。当未指定 x 时,该函数应自动使用基本 matlab 工作区中存在的 x(如果有 x)。

会是好事

function bla(x)
  if(nargin == 0 && exist('x', 'base', 'var'))
    x = fetchin('base', 'x');
  end

  % ...
end

我知道fetchin() 不存在并且exist() 不使用这样的第二个参数来检查某个工作区! 提前非常感谢!

【问题讨论】:

    标签: function matlab scope workspace


    【解决方案1】:

    Matlab 函数evalin 可以做到这一点:

    x=evalin('base','x');
    

    编辑:正如 Col Heather 所提到的,您可以使用 try / catch 语句来处理函数 evalin 可能生成的错误(例如,如果变量不存在),然后检查是否变量的类型正确。

    【讨论】:

    • 啊,这就是“执行表达式”的意思。我以为这仅用于计算,但是是的,您是对的!调用表达式x 只会给出x 的值。谢谢。上述是否是一种为用户简化函数调用的好方法,但仍然让他有可能传递自己的值(以防万一他需要从其他地方调用它)?当没有x 时会发生什么?在致电evalin 之前如何检查?
    • 如果你的用户的x没有被称为x怎么办?
    • 我确保 :-) 为了摆脱存在检查,我想出了简单使用 if(nargin == 0), try, x=evalin('base','x'); catch err, error('Either the workspace var x must exist, or you need to pass x to the function'); end, end 的想法
    【解决方案2】:

    检查调用者/基础中是否存在变量可以通过以下方式完成:

       existStr=sprintf('exist(''%s'', ''var'')==1', varNames{iVar}); % verify variable exists
        isVarExist=evalin(ws, existStr);
        if isVarExist
            valVar=evalin(ws, varNames{iVar});
        else
            valVar=[];
        end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2015-07-30
      • 2016-10-25
      • 2012-08-20
      相关资源
      最近更新 更多