Calculate Euclidean distance matrix in C

本小妞迷上赌 提交于 2021-02-17 06:37:27

问题


I would like to convert this code which is written in MATLAB to 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

The output is as follows:

    0    9   19
    9    0   10
   19   10    0

Here is what I came up with in 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;
}

but it displays an empty array:

0 0 0                                                     
0 0 0                                                                                       
0 0 0

Where is my mistake?


回答1:


There are a couple of problems with your code.

  1. I think, your input data for the matrix is supposed to be matrix = [1 2 3; 4 5 6; 7 8 10], however input data is different in your code (observe the last element; 10 in assignment becomes 9 in your code).

  2. Those points, I think, are spatial (like x, y & z coordinates). So, you need a third loop; first for points in the outer loop point_1 = { 1, 2, 3 }, ... etc, second for points in the inner loop ... point_2 = { 4, 5, 6 }... etc, and a third one for three coordinates x = 1, y = 2, z = 3.

  3. sqrt returns a double. You'd better cast the returning value to int like (int).

  4. As @sahwahn pointed; you compute the distance but never save the value.

Your nested loop structure may look like;

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;
    }
}

BTW; formula for a true distance computation in spatial coordinates is: square root of (the sum of the squares of (the coordinate difference)), not the sum of (square root of (the squares of (the coordinate difference))).

Because I was unsure about the assignment, I stick to the info given in the question. Logically, for a true distance computation, your inner loop needs to be;

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);


来源:https://stackoverflow.com/questions/60510727/calculate-euclidean-distance-matrix-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!