我想将用 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
我的错误在哪里?
您的代码存在一些问题。
我认为,你的矩阵输入数据应该是matrix = [1 2 3; 4 5 6; 7 8 10]
,但是输入数据在您的代码中有所不同(观察最后一个元素;10
在作业中变成9
在你的代码中)。
我认为这些点是空间的(如 x、y 和 z 坐标)。确实如此,你需要第三个循环;首先对于外循环中的点point_1 = { 1, 2, 3 }, ...
等等,第二个是内循环中的点... point_2 = { 4, 5, 6 }...
等等,第三个用于三个坐标x = 1, y = 2, z = 3
.
sqrt
返回一个双精度值。你最好将返回值转换为 int 像(int)
.
正如@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))
, not 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)