请问matlab里遇到这个问题要怎么解决?
函数或变量 'h2' 无法识别。
function GN3Dplot(x,nNeg,nPos,xp,yp,zp,textFlag)
% BZ: if standardized
% function
if size(x,2) < 3
error('dim(x) < 3!!!');
end
n = nPos+nNeg;
target = [zeros(nNeg,1);ones(nPos,1)];
% plot
figure; %三维作图
for i = 1:n
if target(i) == 1
h1 = stem3(x(i,1),x(i,2),x(i,3),'filled','-r');
hold on;
else
% h2 = stem3(x(i,1),x(i,2),x(i,3),'filled','-b');
h2 = stem3(x(i,1),x(i,2),x(i,3),'-.b');
hold on;
end
if textFlag == 1
text(x(i,1)+xp,x(i,2)+yp,x(i,3)+zp,num2str(i));
end
end
legend([h1 h2],'Positive','Negative');
xpp = (max(x(:,1))-min(x(:,1)))/10;
ypp = (max(x(:,2))-min(x(:,2)))/10;
zpp = (max(x(:,3))-min(x(:,3)))/10;
xlim([min(x(:,1)) - xpp,max(x(:,1)) + xpp]);
ylim([min(x(:,2)) - ypp,max(x(:,2)) + ypp]);
zlim([min(x(:,3)) - zpp,max(x(:,3)) + zpp]);
grid on; grid minor;
hold off;
end
出错 GN3Dplot (line 24)
legend([h1 h2],'Positive','Negative')
你不是用了一个if-else分别对h1和h2赋值嘛,h2没有被定义,就表示else那种情况没有出现呗,为了避免这个问题可以给h2和h1都赋个初值,码字不易,有用希望采纳一下
【以下回答由 GPT 生成】
问题分析:
在给函数GN3Dplot
编写代码时,我们发现变量h1
和h2
用于存储stem3
函数的返回值,然后在图例中使用这些返回值进行标注。然而,在代码中只有当target(i)
等于1时,h1
才会被赋值,而当target(i)
不等于1时,h2
则没有赋值的机会,因此在图例中无法识别h2
这个变量。
修改方案:
为了解决这个问题,我们可以在循环之前先对h1
和h2
定义一个初始值,然后在循环中根据条件分别赋值。这样做的目的是保证h1
和h2
都有被赋值的机会,从而避免了无法识别的问题。
以下是修改后的代码:
function GN3Dplot(x, nNeg, nPos, xp, yp, zp, textFlag)
% BZ: if standardized
% function
if size(x, 2) < 3
error('dim(x) < 3!!!');
end
n = nPos + nNeg;
target = [zeros(nNeg, 1); ones(nPos, 1)];
% plot
figure; % 三维作图
h1 = []; % 初始化h1
h2 = []; % 初始化h2
for i = 1:n
if target(i) == 1
h1 = stem3(x(i, 1), x(i, 2), x(i, 3), 'filled', '-r');
hold on;
else
h2 = stem3(x(i, 1), x(i, 2), x(i, 3), '-.b');
hold on;
end
if textFlag == 1
text(x(i, 1)+xp, x(i, 2)+yp, x(i, 3)+zp, num2str(i));
end
end
legend([h1 h2], 'Positive', 'Negative');
xpp = (max(x(:, 1))-min(x(:, 1)))/10;
ypp = (max(x(:, 2))-min(x(:, 2)))/10;
zpp = (max(x(:, 3))-min(x(:, 3)))/10;
xlim([min(x(:, 1)) - xpp, max(x(:, 1)) + xpp]);
ylim([min(x(:, 2)) - ypp, max(x(:, 2)) + ypp]);
通过以上修改,我们在循环之前给h1
和h2
定义了一个初始值,解决了函数或变量无法识别的问题。
请注意,虽然这个修改可以解决问题,但这只是一个简单的修复方案。在实际开发中,我们需要考虑代码结构,确保变量名的一致性和可读性。