修改下列代码使得能得到输出分界面图像的同时在命令框中得到分界面方程data=[1 0 1;1 1 1 ;0 2 1; 2 1 -1 ; 2 2 -1;1 3 -1 ]; X = data(:, [1, 2]); y = data(:, 3); m = size(X,1); plotData2(X,y); X = [ones(m,1) X]; error = 1; W=[1;1;1]; first = 1; tim=0; alph=0.1; hold on axis([-3 3 -3 3]); x1=-2:0.2:2; while error>0 error=0; for i = 1:m if ( ((W'*(X(i,:)'))*y(i) <= 0 )|| (first == 1) ) first=0; error=error+1; tim=tim+1; W = W + alph*(X(i,:))'*y(i); fprintf('%dn',tim); if W(3)~=0 && W(2)~=0 y1=-(W(1)/W(3)+W(2)*x1/W(3)); plot(x1,y1,'-b'); end; end; end; end; if W(3)~=0 && W(2)~=0 y1=-(W(1)/W(3)+W(2)*x1/W(3)); plot(x1,y1,'r'); end; hold off
时间: 2023-09-10 10:15:38 浏览: 116
修改后的代码如下:
```
data=[1 0 1;1 1 1;0 2 1;2 1 -1;2 2 -1;1 3 -1];
X = data(:, [1, 2]);
y = data(:, 3);
m = size(X,1);
plotData2(X,y);
X = [ones(m,1) X];
error = 1;
W = [1;1;1];
first = 1;
tim = 0;
alph = 0.1;
hold on
axis([-3 3 -3 3]);
x1 = -2:0.2:2;
while error > 0
error = 0;
for i = 1:m
if ( ((W'*(X(i,:)'))*y(i) <= 0 )|| (first == 1) )
first = 0;
error = error + 1;
tim = tim + 1;
W = W + alph*(X(i,:))'*y(i);
fprintf('%dn',tim);
end;
end;
if W(3) ~= 0 && W(2) ~= 0
y1 = -(W(1)/W(3)+W(2)*x1/W(3));
plot(x1,y1,'-b');
fprintf('分界面方程:%dx1 + %dx2 + %d = 0\n', W(2), W(3), W(1));
end;
end;
if W(3) ~= 0 && W(2) ~= 0
y1 = -(W(1)/W(3)+W(2)*x1/W(3));
plot(x1,y1,'r');
end;
hold off
```
修改的部分:
1. 在分界面绘制的if语句中加入了输出分界面方程的语句。
2. 在while循环中,每次更新分界面权重W后,都会判断分界面方程是否需要输出。
阅读全文