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

How can I avoid unnecessarily checking the same if-statement in my while loop?

我想在 MATLAB 中实现 k 均值聚类,目前我有一个如下所示的函数:

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 的值?

还有我可以用来计算数据集中每一行的 Pearson 相关系数的 1-liner/函数吗?

您可以简化测试:

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 的比较)。

我会根据比较在循环之前定义一个 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