如何避免在while循环中不必要地检查相同的if语句?

时间:2016-01-02 02:30:33

标签: algorithm matlab k-means

我想在MATLAB中实现k-means聚类,目前我的函数看起来像这样:

function clusters = kmeans(k, data, measure)
...
iterate = true;
while (iterate)
    ...
    if(strcmp(measure, "euclidean")
        dists = getEuclideanDists(centroids, data)
    elseif(strcmp(measure, "pearson")
        dists = getModifiedPearson(centroids, data)
    end
    ...
end
end

我只需要检查字符串measure等于一次,但我需要在while循环中使用if语句的主体,因为centroids的值在while循环期间发生了变化,反过来,dist也是如此。是否有更有效的方法只进行一次检查,但不断更新dist

的值

还有一个1-liner /函数可以用来计算我数据集中每行的Pearson Correlation Coefficient?

2 个答案:

答案 0 :(得分:2)

我根据比较在循环之前定义function handle

function clusters = kmeans(k, data, measure)
    ...
    if(strcmp(measure, "euclidean")
        getDists = @getEuclideanDists;
    elseif(strcmp(measure, "pearson")
        getDists = @getModifiedPearson;
    end

    iterate = true;
    while (iterate)
        ...
        dists = getDists(centroids, data);
        ...
    end
end

答案 1 :(得分:0)

您可以简化测试:

douec = strcmp(measure, "euclidean");
dopea = strcmp(measure, "pearson");
while (iterate)
    ...
    if (doeuc) {
        dists = getEuclideanDists(centroids, data)
    elseif (dopea) {
        dists = getModifiedPearson(centroids, data)
    end
    ...
end

或制作两个循环:

if (strcmp(measure, "euclidean")) {
   while (iterate) ...
}
if (strcmp(measure, "pearson")) {
   while (iterate) ...
}
顺便说一下,不确定你对strcmp的使用是你想要的。

此外,如果ueclidean和pearson是唯一的2种可能性,那么简单(if-else)就足够了(不需要进行elseif的比较)。