![]() |
为什么MATLAB会抱怨它“禁止将相同的名称用作函数和变量”?
惠好的。我已经完成了编码。但是似乎有错误。谁能向我解释为什么有错误?这是代码:
Hcurve = cell2mat(get(handles.Mytable3,'Data')); costA = cell2mat(get(handles.Mytable1,'Data')); cost1 = str2num(get(handles.input2_editText,'String')); cost2 = str2num(get(handles.input3_editText,'String')); cost3 = str2num(get(handles.input4_editText,'String')); cost4 = str2num(get(handles.input5_editText,'String')); limit = cell2mat(get(handles.Mytable2,'Data')); Pdt = str2num(get(handles.input1_editText,'String')); if isempty(costA) if size(Hcurve,1) == 2 H1 = Hcurve(1,:)*cost1; H2 = Hcurve(2,:)*cost2; H = num2cell([H1;H2]); set(handles.Mytable1,'Data',H) cost = cell2mat(get(handles.Mytable1,'Data')); else if size(Hcurve,1) == 3 H1 = Hcurve(1,:)*cost1; H2 = Hcurve(2,:)*cost2; H3 = Hcurve(3,:)*cost3; H = num2cell([H1;H2;H3]); set(handles.Mytable1,'Data',H) cost = cell2mat(get(handles.Mytable1,'Data')); else if size(Hcurve,1) == 4 H1 = Hcurve(1,:)*cost1; H2 = Hcurve(2,:)*cost2; H3 = Hcurve(3,:)*cost3; H4 = Hcurve(3,:)*cost4; H = num2cell([H1;H2;H3;H4]); set(handles.Mytable1,'Data',H) cost = cell2mat(get(handles.Mytable1,'Data')); else cost = costA; end end end end if size(cost,1) == 1 set(handles.text8,'String','At Lease Two Generators'); 这是发生的错误: ???在编译时,“成本”被确定为变量,并且该变量未初始化。 “ cost”也是函数名称,MATLAB的早期版本将其称为函数。但是,MATLAB 7禁止在相同的上下文中使用与函数和变量相同的名称。 如果size(cost,1)== 1,则==> fyp_editor> Mybutton_Callback错误为131 96 feval ==> gui_mainfcn错误(varargin {:}); ==> fyp_editor在42 gui_mainfcn(gui_State,varargin {:})时出错; ==> @(hObject,eventdata)fyp_editor('Mybutton_Callback',hObject,eventdata,guidata(hObject))中的错误 ???评估uicontrol回调时出错 [B]回答:[/B] 您可能遇到的问题是costA不为空,因此if size(cost,1) == 1在调用该行之前,不会嵌套代码的[I]任何[/I]值都将被初始化,并且变量cost将永远不会初始化为任何东西。您可能想对[URL="http://www.mathworks.com/help/techdoc/ref/if.html"]嵌套的if语句[/URL]进行排序,如下所示: if isempty(costA) %# If costA is empty, compute a value for cost if size(Hcurve,1) == 2 ... elseif size(Hcurve,1) == 3 ... elseif size(Hcurve,1) == 4 ... end else cost = costA; %# Will set cost equal to costA if it is not empty end 对于您遇到的异常错误的解释是, cost在您的代码中显示为[I]变量[/I] ,但是似乎也有一个名为cost的[I]函数[/I] 。当您定义一个与函数同名的[URL="http://www.mathworks.com/help/techdoc/matlab_prog/f7-58170.html#bresuvu-6"]变量时[/URL] ,该[URL="http://www.mathworks.com/help/techdoc/matlab_prog/f7-58170.html#bresuvu-6"]变量优先,[/URL]并且在任何计算中都使用该名字时将代替该函数。 即使cost不能在您的条件下初始化为任何东西,MATLAB仍然意识到它[I]可能[/I]是函数中的变量,因此(在MATLAB 7或更高版本中)它不会尝试调用[I]函数[/I] cost 。显然,在旧版本中,如果未初始化具有相同名称的变量,则MATLAB会调用阴影函数。 [url=https://stackoverflow.com/questions/5265363]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 09:05。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.