How to Correctly Calculate Matrix Cofactors in Fortran 90/95?

  • Topic: Fortran 
  • Thread starter Thread starter se00064
  • Start date Start date
  • Tags Tags
    Matrix
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
1 reply · 5K views
se00064
Messages
6
Reaction score
0
OK, so I'm trying to invert a 3x3 matrix in fortran 90/95 (apparently they're not that different). I have a function to calculate the determinant already, and I am trying to write one to find the cofactor of a given element. So far I have the following as a function where ii is the dummy variable representing the row number of the element,jj is the column number and mm is the 3x3 matrix in question:

REAL FUNCTION cof(ii,jj,mm)
IMPLICIT none
REAL, DIMENSION(1:3,1:3) :: mm
INTEGER:: ii,jj,a,b,c,d

a=ii+1
b=ii+2
c=jj+1
d=jj+2

IF (a>3) THEN
a=a-3
END IF

IF (b>3) THEN
b=b-3
END IF

IF (c>3) THEN
c=c-3
END IF

IF (d>3) THEN
d=d-3
END IF

cof=(mm(a,c)*mm(b,d)-mm(a,d)*mm(b,c))

END FUNCTION

The if statements utilise the cyclical nature of the cofactor calculation and the alternating minus and plus signs on each cofactor can be left out because of this.

Basically.. I run the program to calculate all the cofactors of a given 3x3 matrix, and for some reason they come out transposed (ie, the cofactor the program gives for the element m(1,2) is what I calculate to be the cofactor for the element m(2,1)). I've been through the maths a load of times and I can't see what I've done that would cause this, so I just need someone else to have a look please.
I know there are probably other ways of calculating the cofactors, but I have only been programming since September last year and can't really do anything too complicated, hence why I have tried to use such a simple function here. So I just really want help on what the problem is with what I have written myself, as opposed to offering alternatives.
Many thanks in advance.
 
Physics news on Phys.org


Hi there,

Thank you for sharing your code and explaining your problem. I took a look at your function and it seems like you have a small mistake in your indices. In Fortran, the first index in a 2D array represents the row number, while the second index represents the column number. However, in your code, you have swapped the indices for the mm array. This means that when you are accessing the elements in the mm array, you are actually accessing the elements in a transposed manner.

To fix this, you can simply switch the indices in your code. So instead of using mm(a,c), you would use mm(c,a). This should give you the correct cofactors for your matrix.

I hope this helps and good luck with your programming journey!