簡體   English   中英

在 C 中計算歐幾里得距離矩陣

[英]Calculate Euclidean distance matrix in C

我想將此用 MATLAB 編寫的代碼轉換為 C:

matrix = [1 2 3; 4 5 6; 7 8 10]
dis=zeros(9);
for i=1:3
    for j=1:3
        dis(i,j)=sqrt(sum (abs((matrix(i,:)-matrix(j,:))))^2);
    end
end

輸出如下:

    0    9   19
    9    0   10
   19   10    0

這是我在 C 中想到的:

#include <stdio.h>
#include <math.h>

int main() {

  double distance[3][3] = {0};
  double myArray[3][3] = { {1, 2, 3}, {4 , 5, 6}, {7, 8, 9} };

  int i, j;
  for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {

      distance[i][j] = sqrt(pow(myArray[i] - myArray[j], 2));

    }
  }

  for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {

      printf("%f ", distance[i][j]);
      if (j == 2) {
        printf("\n");
      }
    }
  }
  return 0;
}

但它顯示一個空數組:

0 0 0                                                     
0 0 0                                                                                       
0 0 0

我的錯誤在哪里?

您的代碼有幾個問題。

  1. 我認為,矩陣的輸入數據應該是matrix = [1 2 3; 4 5 6; 7 8 10] matrix = [1 2 3; 4 5 6; 7 8 10] matrix = [1 2 3; 4 5 6; 7 8 10]但是輸入數據是在代碼不同(觀察的最后一個元素; 10在分配變得9在代碼)。

  2. 我認為,這些點是空間的(如 x、y 和 z 坐標)。 所以,你需要第三個循環; 第一個用於外循環中的點point_1 = { 1, 2, 3 }, ...等,第二個用於內循環中的點... point_2 = { 4, 5, 6 }...等,第三個對於三個坐標x = 1, y = 2, z = 3

  3. sqrt返回一個雙sqrt值。 你最好將返回值轉換為 int like (int)

  4. 正如@sahwahn 指出的那樣; 您計算距離但從不保存該值。

您的嵌套循環結構可能看起來像;

for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {
        int temp = 0;

        for (k = 0; k < 3; k++) {
            temp += (int)sqrt(pow(myArray[i][k] - myArray[j][k], 2));
        }

        distance[i][j] = temp;
    }
}

順便提一句; 空間坐標中真實距離計算的公式是: square root of (the sum of the squares of (the coordinate difference)) ,而不是square root of (the sum of the squares of (the coordinate difference)) the sum of (square root of (the squares of (the coordinate difference)))

因為我對作業不確定,所以我堅持問題中給出的信息。 從邏輯上講,對於真正的距離計算,您的內部循環需要;

double temp = 0.0f;

for (k = 0; k < 3; k++) {
    temp += pow(myArray[i][k] - myArray[j][k], 2);
}

distance[i][j] = (int)sqrt(temp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM