0

so i have an array [nm] and i need to code in c++ the Euclidean distance between each row and the other rows in the array and store it in a new distance-array [nn] which every cell's value is the distance between the intersected rows. distance-array:

   r0 r1 .....rn
   r0 0
   r1    0
   .       0
   .          0
  rn            0

the Euclidean distance between tow rows or tow records is: assume we have these tow records:

 r0: 1 8 7
 r1: 2 5 3
 r2
 .
 .
 rn

Euclidean distance between r0 and r1 = sqrt((1-2)^2+(8-5)^2+(7-3)^2) to code this i used 4 loops(which i think is too much) but i couldn't do it right, can someone help me to code this without using 3-D array ?? this is my code:

    int norarr1[row][column] = { 1,1,1,2,2,2,3,3,3 };
int i = 0; int j = 0; int k = 0; int l = 0;
for (i = 0; i < column; i++){
    for(j = 0; j < column; j++){
        sumd = 0;
       for (k = 0; k < row; k++) {
            for (l = 0; l < row; l++) {
            dist = sqrt((norarr1[i][k] - norarr1[j][l]) ^ 2);
            sumd = sumd + dist;
            cout << "sumd =" << sumd << "  ";
    }
    cout << endl;
}
disarr[j][i] = sumd;
disarr[i][j] = sumd;
cout << disarr[i][j];
}       
cout << endl;
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Star Ali
  • 1
  • 2

1 Answers1

0

There are several problems with your code. For now, let's ignore the for loops. We'll get to that later.

The first thing is that ^ is the bitwise exclusive or (XOR) operator. It does not do exponentiation like in some other languages. Instead, you need to use std::pow().

Second, you are summing square roots, which is not the correct way to calculate Euclidean distance. Instead, you need to calculate a sum and then take the square root.

Now let's think about the for loops. Assume that you already know which two rows you want to calculate the distance between. Call these r1 and r2. Now you just need to pair one coordinate from r1 with one coordinate from r2. Note that these coordinates will always be in the same column. This means that you only need one loop to calculate the squares of the differences of each pair of coordinates. Then you sum these squares. Finally after this single loop you take the square root.

With that out of the way, we need to iterate over the rows to choose each r1 and r2. Okay, this will take two loops since we want each of these to take on the value of each row.

In total, we will need three for loops. You can make this easier to understand by designing your code well. For example, you can create a class or struct that holds each row. If you know that every row is only three dimensions, then create a point or vector3 class. Now you can write a function which calculates the distance between two points. Finally, store the list of points as a 1D array. In fact, breaking up the data and calculation in this way makes the previous discussion about calculating the distance even easier to understand.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268