![](/img/trans.png)
[英]Determinant of a nxn matrix with function recursion in c programming
[英]Write a function to compute the n'th power of a (nxn)matrix in C
我在2矩阵算法的乘法中添加了for,但似乎不起作用。我需要在不使用指针,内存分配和仅使用基本指令的情况下执行此任务(for,while,...)
void product(double a[][20],double c[][20],int n,int d)
{
int i, j, k, l;
for(l = 1;l <= d; ++l) {
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
c[i][j] = 0;
for(k = 0; k < n; k++) {
c[i][j] += a[i][k]*a[k][j];
}
}
}
}
}
此函数应计算A ^ d并将其存储在c [] [20];中。
您的代码尝试计算A ^(2 ^ d),但是却计算了A ^ 2 d次。
您不能就地进行矩阵乘法,因为在计算结果时,您将覆盖值。 因此,您需要一个副本空间(除非d = 0、1或2)。
将C设置为单位矩阵,如果d = 0则返回。否则设置C = A的副本,分配一个矩阵B,然后对于l = 1到d-1将C复制到B,让C = A *B。
您的代码计算d
次A^2
。 您应该首先将C初始化为单位矩阵,除对角线为1之外,其他所有均为0,然后循环d
乘以C
乘以A
对于此算法的更快版本,请使用整数数学乘以2的幂,以显示将a提高到n的幂的想法:
unsigned int n; /* unsigned to prevent issues with right shift */
b = a; /* a, b, c, t are actually matrices */
c = 1; /* identity matrix */
t; /* temp matrix */
while(n){
if(n&1){ /* if (n&1), c *= b */
t = c*b;
c = t;
}
t = b*b; /* b = b^2 */
b = t;
n >>= 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.