【问题标题】:Distance Between Two Points in MatlabMatlab中两点之间的距离
【发布时间】:2011-11-17 14:07:53
【问题描述】:

我有 2 个向量,一个是 200*2 维度,另一个是 3*2。它们都是笛卡尔坐标系中的点。我想计算前 200 个点和其他 3 个点之间的距离,并将它们存储在一个向量中。我正在使用这样的功能;

for i=1:cur
    for j=1:200
        L(j,i)=sqrt(square(P2(i,1)-C(j,1))+square(P2(i,2)-C(j,2)))
    end
end

其中 cur 是 3 ,P2 是 3*2 向量,C 是 200*2。现在我得到的结果完全错误,但我无法弄清楚其中的问题。任何帮助都会很好,如果有另一种计算方法,我将不胜感激。顺便了解更多信息;

P2 = [2 -2;3 -5 ; -1 3];

另一个是

theta = linspace(0,2*pi,200)';   %'
unitCircle = [cos(theta) sin(theta)];
C = zeros(numel(theta),2,num);

【问题讨论】:

    标签: matlab vector distance


    【解决方案1】:

    square 不是求平方,而是返回方波的值。

    您可以使用pdist2 计算两组观测值之间的成对距离,如下所示:

    X = randn(200, 2);
    Y = randn(3, 2);
    D = pdist2(X,Y,'euclidean'); % euclidean distance
    

    【讨论】:

    • 我刚刚想通了,现在我使用的是 pow2 而不是那个,但是我仍然得到不相关的结果你知道这是怎么回事吗?
    • 也不要使用pow2pow2(x) 返回 2 的 x 次方,而不是 x 的 2 次方。要获得 x 的平方,请使用 x.^2
    【解决方案2】:

    square 函数不是你想要的(它是generates a square wave)。

    要计算数字的平方,请使用^ 运算符:

    x = 3;
    y = x ^ 2;
    disp(y);  % Prints 9
    

    【讨论】:

    • 谢谢,这真的很有帮助,虽然我自己想不出来,但很遗憾:)。
    • @user1001296 - 您应该将答案标记为“已接受”,以正式通知回答者他的答案是最好的。
    【解决方案3】:
    tic
    A = pdist2( X,  X);
    toc
    % method 2
    tic
    n = size(X, 1);
    idx = repmat(1:n, n, 1);
    D = sqrt(sum((X(idx,:)-X(idx',:)).^2, 2));
    D = reshape(D, n, n);
    toc
    find(A-D)
    Elapsed time is 0.021950 seconds.
    Elapsed time is 0.043413 seconds. % and add your satisfaction approximately -0.02 seconds
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      相关资源
      最近更新 更多