Matlab 如何计算迭代次数
我在MATLAB上使用k-means。要处理有效的集群,它需要进行循环,直到集群位置不再改变。循环将显示迭代过程 我想计算在集群过程中发生了多少循环/迭代。以下是循环/迭代处理部分的片段:Matlab 如何计算迭代次数,matlab,variables,iteration,counting,Matlab,Variables,Iteration,Counting,我在MATLAB上使用k-means。要处理有效的集群,它需要进行循环,直到集群位置不再改变。循环将显示迭代过程 我想计算在集群过程中发生了多少循环/迭代。以下是循环/迭代处理部分的片段: while 1, d=DistMatrix3(data,c); %// calculate the distance [z,g]=min(d,[],2); %// set the matrix g group if g==temp, %// if
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 does not 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
我所知道的就是定义迭代变量,然后编写计算部分。但是,我必须在哪里定义变量?怎么做
所有的答案都将不胜感激
谢谢。在循环之前定义,在循环中更新
iterations=0;
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
iterations=iterations+1;
end
fprintf('Did %d iterations.\n',iterations);
执行Matlab循环,直到表达式为false
。一般设置如下所示:
while <expression>
<statement>
end
在
之前还是之后增加循环计数器的问题取决于是否需要它来访问向量条目。在这种情况下,它应该在
之前递增,因为0
在Matlab中不是有效的索引。您的“循环/迭代”是什么意思?您有两个不同的循环(while
中的for
)。是否还要计算循环迭代的次数?
LoopCounter = 0;
while <expression>
<statement>
LoopCounter = LoopCounter + 1;
end