【问题标题】:How to count the number of iterations如何计算迭代次数
【发布时间】:2013-06-17 12:33:05
【问题描述】:

我在 MATLAB 上使用 k-means。为了处理有效的簇,它需要循环直到簇的位置不再改变。循环将显示迭代过程。

我想计算在该集群过程中发生了多少循环/迭代。下面是循环/迭代处理部分的sn-p:

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

我所要做的就是定义迭代变量,然后编写计算部分。但是,我必须在哪里定义变量?怎么做?

我们将不胜感激所有答案。

谢谢。

【问题讨论】:

  • 你的“循环/迭代”是什么意思?您有两个不同的循环(while 中的for)。是否还要计算for 循环迭代的次数?

标签: matlab variables iteration counting


【解决方案1】:

Matlab while-loop 被执行直到表达式为false。一般设置是这样的:

while <expression>
    <statement>
end

如果要统计进入while循环的次数,最简单的方法是在循环外声明一个变量并在循环内递增:

LoopCounter = 0;

while <expression>
    <statement>
    LoopCounter = LoopCounter + 1;
end

&lt;statement&gt; 之前或之后增加LoopCounter 的问题取决于您是否需要它来访问向量条目。在这种情况下,它应该在 &lt;statement&gt; 之前递增,因为 0 在 Matlab 中不是有效的索引。

【讨论】:

    【解决方案2】:

    在循环之前定义,在循环中更新。

    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);
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2015-05-18
      • 1970-01-01
      • 2013-01-07
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多