Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I need to inverse a matrix given in a file.
The problem is I'm stuck with writing determinant finding algoritm into code.I found this algoritm about finding determinant of nxn matrix. This is what i need:
http://www.maths.surrey.ac.uk/explo...and here:
a11 a12 a13
a21 a22 a23
a31 a32 a33
= a11(a22a33 − a23a32) − a12(a21a33 − a23a31) + a13(a21a32 − a22a31)
Note the pattern of + and − signs.
The general formula is compact, but tedious to compute. Here it is for an n by n matrix A:
detA = ai1Ci1 + ai2Ci2 + · · · + ainCinwhere Cij are referred to as the cofactors and are computed from
Cij = (−1)i+j detMij
The term Mij is known as the ”minor matrix” and is the matrix you get if you eliminate row
i and column j from matrix A. So to find the determinant of e.g. a 4×4 matrix, you end up
calculating a bunch of 3 × 3 matrix determinants (much easier). Obviously you can apply this
technique recursively (probably using a computer).***************
Can some1 please write it into my code or if he has time even complete the full inverse.
I read the matrix from a file into an array "row":
----------------#!/usr/bin/awk -f
BEGIN{}
{
m=1
while (m <= NF){
row[NR,m] = $m
m++
}
}END{}
--------------
thank you.

I got something done, but it only works for 2*2 and 3*3 matrices. There must be a mistake. I used the code I found somewhere:
int determinant(int b[5][5],int m) //FUNCTION TO CALCULATE
DETERMINANT
{
int i,j,sum = 0,c[5][5];
if(m==2)
{ //BASE CONDITION
sum = b[0][0]*b[1][1] - b[0][1]*b[1][0];
return sum;
}
for(int p=0;p<m;p++)
{
int h = 0,k = 0;
for(i=1;i<m;i++)
{
for( j=0;j<m;j++)
{
if(j==p)
continue;
c[h][k] = b[i][j];
k++;
if(k == m-1)
{
h++;
k = 0;
}}
}sum = sum + b[0][p]*pow(-1,p)*determinant(c,m-1);
}
return sum;
}I also used this:
function det( a, n )if n = 2 then
d := a11·a22 - a12·a21
else
d := 0
for i := 1...n do
M1i <-- A with row 1 and column i deleted
d := d + (-1)(i-1)·a1i·det( M1i, n - 1 )
end for
end if
return d
end function
And got my awk code:
function det(a, n) {
if (n == 2) {
d = a[1,1] * a[2,2] - a[1,2] * a[2,1]
print d
}else {
d=0
for(i = 1; i <= n; i++){
k=1
j=1
for (x = 2; x <= n; x++) {
for (z = 1; z <= n; z++){
if (z==i)
{z++}
M[k,j]= a[x,z]
j++}
j=1
k++
}
d= d + miinus1_astmel(i-1)*a[1,i]*det( M, n - 1)
}
return d
}
function miinus1_astmel(n){
vastus=1
for (x=1; x<=n; x++){
vastus=vastus*(-1)
}
return vastus
}Looks the same to me, but somewhere is a mistake.

![]() |
Concate contents with che...
|
Help with AWK to extract ...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |