我想将用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
我的错误在哪里?
答案 0 :(得分:3)
您的代码有几个问题。
我认为您的矩阵输入数据应该为matrix = [1 2 3; 4 5 6; 7 8 10]
,但是代码中的输入数据有所不同(观察最后一个元素;赋值10
变为{{1 }})。
我认为这些点是空间上的(如x,y和z坐标)。因此,您需要第三个循环;
9
等中的点,第二个用于内循环point_1 = { 1, 2, 3 }, ...
等中的点,第三个用于三个坐标... point_2 = { 4, 5, 6 }...
中的点。
x = 1, y = 2, z = 3
返回一个双精度值。您最好像sqrt
一样将返回值强制转换为int。
正如@sahwahn所指出的;您可以计算距离,但永远不会保存该值。
您的嵌套循环结构可能看起来像;
(int)
顺便说一句;在空间坐标中进行真实距离计算的公式为:
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))
。
由于我不确定任务,所以我坚持问题中给出的信息。从逻辑上讲,对于真正的距离计算,您的内部循环必须是;
the sum of (square root of (the squares of (the coordinate difference)))