我正在MATLAB上使用k-means。为了处理有效的集群,它需要执行一个循环,直到集群位置不再改变。因此,循环超过10次迭代是可能的。这可能需要很长时间。
所以,我想让用户设置迭代。示例:用户输入'3'进行迭代,则迭代将持续到3次迭代。下面是迭代过程的代码片段:
while 1,
d=DistMatrix3(data,c); % calculate the distance
[z,g]=min(d,[],2); % set the matrix g group
if g==temp, % if the iteration doesn't change anymore
break; % stop the iteration
else
temp=g; % copy the matrix to the temporary variable
end
for i=1:k
f=find(g==i);
if f % calculate the new centroid
c(i,:)=mean(data(find(g==i),:),1);
end
end
end
我所知道的是我必须定义一个变量来让用户输入迭代的次数。该变量将用于循环/迭代过程。我已经尝试过将while 1
删除到for i=1:iteration
。但还是不像我想的那样。有人知道怎么做吗?
请大家踊跃回答。
谢谢。
你差一点。for i=1:iteration
不起作用的原因是您在内部循环中使用了变量i
: for i=1:k
。当内部循环结束时,无论外部循环在做什么,i
的值都将为k
。大多数编译器都会抱怨这样的事情-但默认情况下Matlab没有…要解决这个问题,需要做的就是为外部循环使用一个唯一的变量,例如itNum
:
for itNum = 1:iterationCount % <<<< new line, ensures at most "iterationCount" iterations
d=DistMatrix3(data,c); % calculate the distance
[z,g]=min(d,[],2); % set the matrix g group
if g==temp, % if the iteration doesn't change anymore
break; % stop the iteration
else
temp=g; % copy the matrix to the temporary variable
end
for i=1:k
f=find(g==i);
if f % calculate the new centroid
c(i,:)=mean(data(find(g==i),:),1);
end
end
end % end of for itNum... loop
顺便说一句,当人们使用i
作为变量时,这是我最讨厌的事情。Matlab有一个内置变量i
,其值为sqrt(-1)
。当你给它赋一个新值时,它失去了内在值,这可能会破坏其他代码…
for i=1:k
f=find(g==i);
if f % calculate the new centroid
c(i,:)=mean(data(find(g==i),:),1);
end
end
通常被认为是低效的。如果可能的话,避免使用find
;如果你要使用它,确保你使用了结果。例如(避免使用find
):
for i=1:k
if any(g==i)
% calculate the new centroid
c(i,:)=mean(data(g==i,:), 1);
end
end
或者(重用find
的结果):
for i=1:k
f = find(g==i)
if f
% calculate the new centroid
c(i,:)=mean(data(f,:), 1);
end
end
哪一个更有效将取决于g
的大小…