Matlab 无环矩阵运算
我有一个包含5个点的几何坐标的矩阵Matlab 无环矩阵运算,matlab,matrix,Matlab,Matrix,我有一个包含5个点的几何坐标的矩阵 centroids = [x1,x2;...;x5,y5] 我想建立一个矩阵,其中包含与所有其他点的距离 distance = inf pt1-pt2 pt1-pt3 pt1-pt4 pt1-pt5 pt2-pt1 inf pt2-pt3 pt2-pt4 pt2-pt5 pt3-pt3 pt3-pt2 inf pt
centroids = [x1,x2;...;x5,y5]
我想建立一个矩阵,其中包含与所有其他点的距离
distance =
inf pt1-pt2 pt1-pt3 pt1-pt4 pt1-pt5
pt2-pt1 inf pt2-pt3 pt2-pt4 pt2-pt5
pt3-pt3 pt3-pt2 inf pt3-pt4 pt3-pt5
pt4-pt1 pt4-pt2 pt4-pt3 inf pt4-pt5
pt5-pt1 pt5-pt2 pt5-pt3 pt5-pt4 inf
我使用inf,因为我想用每一行的索引[value,index]=min(距离(…))取min
目标是有一个这样的最终矩阵:
result =
indice_of_the_closest dist
indice_of_the_closest dist
indice_of_the_closest dist
indice_of_the_closest dist
indice_of_the_closest dist
我通过一个循环来实现这一点,但我需要一些帮助来实现这一点而不需要循环
最好的祝愿如果你没有统计工具箱,你可以这样做
% Compute the pair-wise distances
d = sqrt((x(:,1) - x(:,1).').^2 + (x(:,2) - x(:,2).').^2);
% If you are on MATLAB < 2016b
% d = sqrt(bsxfun(@minus, x(:,1), x(:,1).').^2 + bsxfun(@minus, x(:,2), x(:,2).').^2);
% Set the diagonal to Inf
d(logical(eye(size(d)))) = Inf;
% Find the minimum distance and index
[mindist, ind] = min(d, [], 1);
% Create the output matrix
result = [ind(:), mindist(:)];
你能更详细地解释一下MATLAB<2016b的解决方案吗?我不能完全理解。谢谢
[inds, dists] = knnsearch(x, x, 'k', 2);
result = [inds(:,2), dists(:,2)];