I have a 2D Array (inputMatrix with x rows and y columns) and need to subtract all vectors(rows) with eachother.
Here's the input:
1,5
3,7
2,3
6,5
4,7
The output(a distance matrix) should look like:
subtraction[0][0] = {0,0} // first row - first row
subtraction[0][1] = {-2,-2} // first row - 2nd row -> {1,5}-{3,7}=-2,2
subtraction[0][2] = {-1,2} // first row - 3rd row
...
subtraction[4][2] = {2,4}
subtraction[4][3] = {-2,2}
subtraction[4][4] = {0,0}
However i'm having a problem on storing the values, since subtraction[row][col] values are being overwritten on the "col for-loop". Also a note, each subtraction index is getting as output another array.
for(int row = 0; row < inputMatrix.length; row++){
for(int col = 0; col < inputMatrix[0].length; col++){
subtraction[row][col] = inputMatrix[0][row] - inputMatrix[row][col];
System.out.print(subtraction[row][col] + " ");
}
System.out.print("\n");
}
Based on your description of the output, you need a 3-dimensional array to store the output, since for each pair of input rows, you are producing an output row.
for(int row1 = 0; row1 < inputMatrix.length; row1++){
for(int row2 = 0; row2 < inputMatrix.length; row2++){
for(int col = 0; col < inputMatrix[0].length; col++){
subtraction[row1][row2][col] = inputMatrix[row1][col] - inputMatrix[row2][col];
}
}
}
If you must have a two dimensional output, you can flatten the output :
int outputRow = 0;
for(int row1 = 0; row1 < inputMatrix.length; row1++){
for(int row2 = 0; row2 < inputMatrix.length; row2++){
for(int col = 0; col < inputMatrix[0].length; col++){
subtraction[outputRow][col] = inputMatrix[row1][col] - inputMatrix[row2][col];
}
outputRow++;
}
}
subtraction[row][col] = inputMatrix[0][row] - inputMatrix[**row**][**col**];
您在这里混合了索引。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.