您提出的算法实际上不会找到相距最大距离的两个坐标。例如,如果距离最大的两个点有z = 0 怎么办?
这里有两个解决方案,一个实际上会给你两个最大距离的点,另一个是你的北极-南极算法的实现。请注意,在这两种解决方案中,我给出的函数都返回候选点的索引,而不是点本身。您可以自己获得积分
north = A(iN, :);
south = A(iS, :);
解决方案 1:找到距离最大的两个点
尝试使用file exchange. 中的distmat 函数它需要一个N x D 点数组A,其中N 是点数,D 是维度,并返回一个@ 987654329@ 距离数组dist,其中dist(i, j) 是A(i,:) 和A(j,:) 之间的距离。 distmat 有 4 种不同的算法可用于生成矩阵,具体取决于哪种算法可以提供最佳性能。
您可以使用此函数创建一个距离矩阵,然后使用max 定位最大距离的候选者。然后你可以用任何你喜欢的方式打破关系。
在下面的函数中,我找到了所有距离最大的点。如果有不止一对,我会根据候选者之间的 x-y 距离打破平局。
function [iN, iS] = poles(A)
% create the distance matrix
dist = distmat(A);
% find all candidate pairs of north and south poles
[~, iMax] = max(dist(:));
[iN, iS] = ind2sub(size(dist), iMax);
% If there is only one, you are done, otherwise break the ties.
if length(iMax) == 1
return
end
%
% break ties by the euclidean distance of the x-y coordinates
% note that this may not result in a unique set of north and south poles,
% but you can always break further ties.
north = A(iN, 1:2);
south = A(iS, 1:2);
tieBreak = sum(abs(north-south).^2, 2);
[~, iMax] = max(tieBreak);
iN = iN(iMax);
iS = iS(iMax);
end
解决方案2:找到“北极”和“南极”
此解决方案还使用distmat 函数。首先,它找到具有最大和最小 z 值的点。如果没有关系,那么它就会停止。否则,它会找到具有最大距离的一对“北”和“南”点,并如上所述进行抢七。
function [iN, iS] = poles(A)
% find the min and max z values
[~, iMaxZ] = max(A(:, 3));
[~, iMinZ] = min(A(:, 3));
iMaxZ = iMaxZ(:);
iMinZ = iMinZ(:);
if length(iMaxZ) == 1 && length(iMinZ) == 1
iN = iMaxZ;
iS = iMinZ;
return
end
nMax = length(iMaxZ);
nMin = length(iMinZ);
% put the north and south poles together
northSouth = A([iMaxZ; iMinZ], :);
% find the distance between them
dist = distmat(northSouth);
% restrict to only north-south pairs
dist = dist(1:nMax, nMax+1:end);
% find the maximum distance
[~, iMaxDist] = max(dist(:));
[iN, iS] = ind2sub(size(dist), iMax);
if length(iMaxDist) == 1
return
end
% break ties by the euclidean distance of the x-y coordinates
% note that this may not result in a unique set of north and south poles,
% but you can always break further ties.
north = A(iN, 1:2);
south = A(iS, 1:2);
tieBreak = sum(abs(north-south).^2, 2);
[~, iMax] = max(tieBreak);
iN = iN(iMax);
iS = iS(iMax);
end