【问题标题】:How to set the scope of a variable in a Matlab function如何在 Matlab 函数中设置变量的范围
【发布时间】:2013-01-28 21:35:05
【问题描述】:

我观察到在 Matlab 函数和命令窗口中运行相同代码时出现奇怪的行为。 How does scoping in Matlab work? 中已经描述了它,但我不明白如何解决我的具体问题。 代码如下:

exporteddata.m  %File created by an external program 
                %to export data in Matlab format

surface = struct('vertices', [...]) ; 
                         %I can't specify in the external program 
                         %the name of the variable, it's always "surface"

我的实际代码是:

   myfunction.m 

   function output = myfunction(input)
   load(input);
   n = size(surface.vertices);
  ....

运行时

myfunction('exporteddata.m'); 

我收到以下错误:

???类 hg.surface 没有合适的方法、属性或字段顶点。

在命令窗口或调试模式下运行相同的指令时,代码运行良好。

如何在函数中指定我需要工作区中存在的变量表面,而不是 Matlab 函数?

【问题讨论】:

    标签: matlab overloading scope


    【解决方案1】:

    首先,我必须指出,surface 是 MATLAB 中的内置函数,所以重载它只是……不好。糟糕,糟糕,糟糕!

    话虽如此,MATLAB 解释器在解析变量名称方面做得非常好,并且通常会正确地将它们与函数名称区分开来。那么,您的问题出在哪里?
    我相信您使用了错误的函数:load 是一个将数据从 MAT 文件加载到工作区的函数。它不适合 m 文件。由于未正确执行“exportedata.m”,surface 从未被创建为变量,因此 MATLAB 将其标识为函数名称。如果要执行“exporteddata.m”,只需输入:

    exportedata
    

    如果你想运行文件名存储在input的文件,你可以使用run:

    run(input)
    

    通过在myfunction 内执行run(input),surface 应该在myfunction 的本地范围内创建,并且它应该可以工作。

    编辑:
    我刚刚测试了它,解释器仍然感到困惑。所以变量名称解析的问题仍然存在。这是一个解决方法:

    function output = myfunction(input)
       surface = 0;                     %// <-- Pay attention to this line
       run(input);
       n = size(surface.vertices);
    

    预定义surface 允许解释器将其识别为整个函数中的变量。我试过了,效果很好。

    【讨论】:

    • 问题是变量surface在run(input)之前不存在,所以不能作为参数传递给函数!
    • 我想到的唯一选择是将exporteddata,m 作为文本文件打开并将“surface”替换为“myVar”。但如果可能的话,我有兴趣利用 Matlab 范围机制
    • 好的,那么您能否添加更多关于您如何运行exportedata.m 和myfunction.m 的详细信息(在您的问题中)? myfunction 是从也调用 exportedata 的外部脚本调用的吗?
    • 对不起,我要编辑它。无论如何, input=exporteddata.m ;我的函数(输入);
    • 是的,现在可以了!谢谢!您使我免于弄乱我的代码并实现搜索/替换功能!
    猜你喜欢
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多