MATLAB名称冲突:“错误的参数数量”

似乎我有一个名为“annotation”的变量和内置的MATLAB函数“annotation”中的一个变量名称相冲突。MATLAB名称冲突:“错误的参数数量”

在我的函数中,我加载一个包含变量注释的.mat文件,然后尝试将它用作另一个函数的参数。一个最小的工作示例如下:

function test() 

filenames = { 'file1.mat', 'file2.mat', 'file3.mat' };

for i = 1:numel(filenames)

in_file = char(filenames{i});

out_file = strrep(in_file, '.mat', '_out.mat');

prepare(out_file); % do something with the out file

load(out_file); % contains one variable named "annotation"

which annotation % just to be sure

other_function(annotation);

end

end

function prepare(filename)

annotation = rand(25, 1);

save(filename);

end

function other_function(annotation)

whos % just a stub - see whether it has been called

end

现在,在我的功能准备我确信该文件包含一个名为“注释”的变量。当我将它加载到主函数的循环中时,“which”命令告诉我它作为变量存在,但在other_function的调用中,MATLAB试图调用函数“annotation”:

注解是一个变量。

???使用错误==>注释在71

没有足够的输入参数

错误==>测试在14

 other_function(annotation); 

我很困惑,因为我使用的变量名“注释”在我的程序的几个部分,也作为函数调用的参数。我能想象的唯一解释是MATLAB以某种方式预编译我的代码 - 在“编译时”,变量“注释”不可见。但是,在运行时发现可以从“which”命令的输出中看到。

任何帮助将不胜感激!提前谢谢了。

注意:我正在使用MATLAB 7.12.0(R2011a)。

回答:

这有点奇怪!我找到了同样的东西。基本上,工作区变量不应该在函数内部(尽管它们来自内部脚本)。

如果你这样做load(out_file)这是加载该文件的内容到工作区。所以他们不应该在范围内,我相信。因此,我很惊讶which(annotation)称它为一个变量,但并不感到惊讶,因为annotation超出了范围。 (实际上,它看起来像Matlab的排序 - 把变量放在范围内。)

我认为你对annotation的某种预处理的想法听起来似乎合理。例如,如果你用eval('other_function(annotation);')代替other_function(annotation),那么它可能会工作(尽管我并不是说你应该使用eval,永远)。

解决这将是这样做的最佳方式:

data = load(out_file); 

annotation = data.annotation;

因此,负载out_file成一个结构,然后从那里访问变量。

回答:

这是一个精美难懂的问题!这是Mathwork的糟糕设计。我甚至会把它称为一个bug,有趣的是看看他们是否同意。

简短回答:您可以通过在您的代码中的任意位置添加annnotation = 2;行来修复此问题,此代码位于load(out_file);行以上。或者annotation = "roger";annotation = false;,只要您明确强制将其作为您代码中的变量,那么使用哪种类型的变量进行注释并不重要。

您写的代码没有明确引用变量annotationannotation恰好是您加载到函数工作区的matlab文件中的一个变量的名称。不知何故,这不会抛出运行时错误,它只是错误的,我会称之为错误,但matlab可能会说是一个记录的限制。请参阅他们的文档http://www.mathworks.com/help/techdoc/matlab_prog/f4-39683.html#f4-75258并告诉我您的想法。这个文档似乎适用于嵌套函数,你的主要功能当然不是。 CLEARLY你的行other_function(annotation)应该看到annotationwhich annotation相同的范围内,放置在它看到的正上方。 (我只是做了那个测试,它说annotation is a variable)。

这里是一个很小的程序,显示问题:

function test() 

prepare('test.mat'); % writes i

load('test.mat'); % contains one variable named "annotation"

which annotation

other_function(annotation);

end

function prepare(filename)

annotation = 42; % the answer is 42

save(filename);

end

function other_function(poodle)

disp(poodle);

end

我邀请您使用页面上的“报告错误”链接http://www.mathworks.com/support/bugreports提交这个bug报告!如果你不想,我会报告,只是让我知道。

回答:

这是(现在呢?)记录的行为:

http://www.mathworks.com/help/matlab/import_export/troubleshooting-loading-variables-within-a-function.html

以上是 MATLAB名称冲突:“错误的参数数量” 的全部内容, 来源链接: utcz.com/qa/258657.html

回到顶部