How can I raise a matrix to the nth power in C? Here is what I have so far. wher
ID: 3890042 • Letter: H
Question
How can I raise a matrix to the nth power in C?
Here is what I have so far.
where:
dim = dimensions of the matrix
powernum = the power the matrix is being raised to.
matrix = the matrix.
int matrixAns[dim][dim];
int i,c,d,k;
int sum = 0;
for (i = 0; i < powernum; i++)
{
for ( c = 0 ; c < dim ; c++ )
{
for (d = 0 ; d < dim ; d++ )
{
for ( k = 0 ; k < dim ; k++ )
{
sum += matrix[c][k]*matrix[k][d];
}
matrixAns[c][d] = sum;
sum = 0;
}
}
for ( c = 0 ; c < dim; c++ ) {
for ( d = 0 ; d < dim ; d++ ) {
matrix[c][d] = matrixAns[c][d];
matrixAns[c][d] = 0;
}
}
}
Please help me, thank you.
Explanation / Answer
#include <stdio.h>
int a[10][10],c[10][10],r;
void mul() //to multiply 2 matrices
{
int b[10][10],i,j,k;
for(i=0;i < r;i++)
{
for(j=0;j < r;j++)
{
b[i][j]=0;
for(k=0;k < r;k++)
b[i][j]=b[i][j]+a[i][k]*c[k][j]; //to multiply a and c
}
}
for(i=0;i < r;i++)
{
for(j=0;j < r;j++)
c[i][j]=b[i][j]; //assign value of c as a*c
}
}
int main()
{
int i,j,n;
scanf("%d",&r); //order of matrix
for(i=0;i < r;i++)
{
for(j=0;j < r;j++)
{
scanf("%d",&a[i][j]); //inputting the matrix
if(i==j) //assigning c as identity matrix
c[i][j]=1;
else
c[i][j]=0;
}
}
scanf("%d",&n); //inputting power
for(i=0;i < n;i++)
mul(); //multiplying the matrix n time
for(i=0;i < r;i++)
{
for(j=0;j < r;j++)
printf(" %d",c[i][j]); //printing answer
printf(" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.