如何在Matlab函数中设置变量的范围
在Matlab函数和命令窗口中运行相同代码时,我观察到一种奇怪的行为。已经在中描述了,但我不明白如何解决我的具体问题。 代码如下:如何在Matlab函数中设置变量的范围,matlab,overloading,scope,Matlab,Overloading,Scope,在Matlab函数和命令窗口中运行相同代码时,我观察到一种奇怪的行为。已经在中描述了,但我不明白如何解决我的具体问题。 代码如下: exporteddata.m %File created by an external program %to export data in Matlab format surface = struct('vertices', [...]) ; %I can't specify
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中的一个内置函数,因此重载它只是。。。糟糕。坏,坏,坏 话虽如此,MATLAB解释器在解析变量名方面做得相当好,并且通常正确地将变量名与函数名区分开来。你问,你的问题出在哪里?
我认为您使用了错误的函数:是一个将MAT文件中的数据加载到工作区的函数。它不适用于m文件。由于未正确执行“exportedata.m”,因此,
surface
从未被创建为变量,因此MATLAB将其识别为函数名。如果要执行“exportedata.m”,只需键入:
exportedata
如果要使用存储在input
中的文件名运行文件,可以使用:
通过从myfunction
内执行run(input)
,应在myfunction
的本地范围内创建曲面,并且该曲面应能工作
编辑:
我刚刚测试过它,但口译员仍然感到困惑。因此,变量名解析的问题仍然存在。这里有一个解决方法:
function output = myfunction(input)
surface = 0; %// <-- Pay attention to this line
run(input);
n = size(surface.vertices);
函数输出=myfunction(输入)
表面=0;%//问题是变量曲面在运行(输入)之前不存在,所以我不能将其作为参数传递给函数!我想到的唯一选择是将exporteddata,m作为文本文件打开,并将“surface”替换为“myVar”。但是我有兴趣利用Matlab的作用域机制,如果可能的话,那么您可以添加更多关于如何运行exportedata.m
和myfunction.m
的详细信息吗?myfunction
是否从同时调用exportedata
的外部脚本调用?抱歉,我要编辑它。无论如何,input=exporteddata.m;myfunction(输入);是的,现在它工作了!非常感谢。你救了我,使我免于混乱的代码和实现搜索/替换功能!
function output = myfunction(input)
surface = 0; %// <-- Pay attention to this line
run(input);
n = size(surface.vertices);