user991852
user991852

Reputation: 107

handling of many matrices in fortran program

this is my program

program matrix
real :: J1(38,38),J2(38,29),J3(29,38),J4(29,29)
real :: J13(38,1),J23(29,1),J33(1,68),Jac(68,68)
!!all matrices contains some values except Jac

Jac=[J1 J2 J13
     J3 J4 J23
     J33      ]
end program matrix

Now i want to put all these matrices into 1 matrix Jac(68,68) so that Jac=[J1 J2 J13 J3 J4 J23 J33 ] what should be the fortran code..please help me.

Upvotes: 1

Views: 317

Answers (3)

High Performance Mark
High Performance Mark

Reputation: 78354

Or, if you don't like writing loops you could write;

Jac(1:38,1:38) = J1
Jac(1:38,39:38+29) = J2

and so forth.

EDIT

I can't tell from what you've posted if this bit will be of interest, but I infer a level of Fortran knowledge which does not include this ...

you could define:

real, target :: jac(68,68) 
real, dimension(:,:), pointer :: j1, j2, j3, j4, j13, j23, j33

and use these sub-arrays like this:

j1 => jac(1:38,1:38)
j33 => jac(1,:)

etc. This way you have only one copy of the data in memory, which for such small arrays probably doesn't matter. And it is the wrong approach if the contents of the subarrays and of the super array should be different.

Upvotes: 10

Azrael3000
Azrael3000

Reputation: 1897

To put it a bit more concise you can also use

JAC( 1:38, 1:38) = J1 (1:38,1:38)
JAC( 1:38,39:67) = J2 (1:38,1:29)
JAC( 1:38,   68) = J13(1:38,   1)
JAC(39:67, 1:38) = J3 (1:29,1:38)
JAC(39:67,39:67) = J4 (1:29,1:29)
JAC(39:67,   68) = J23(1:29,   1)
JAC(   68, 1:68) = J33(   1,1:68)

If you have bigger arrays, where copying might not be a good idea, I suggest you write a function that converts indices automatically. For fun I added a custom type MATRIX containing all the submatrices without specifying it explicitly below. So you have

REAL FUNCTION JAC(I,J, JAC_MAT)
  INTEGER, INTENT(IN) :: I,J
  TYPE(MATRIX), INTENT(IN) :: JAC_MAT
  IF(I.LE.38.AND.J.LE.38)THEN
    JAC = JAC_MAT%J1(I,J)
  ELSEIF(I.LE.38.AND.J.LE.67)THEN
    JAC = JAC_MAT%J2(I,J-38)
  ...
  ENDIF
END FUNCTION

Upvotes: 3

user210870
user210870

Reputation:

You will need to iterate over Jac and assign elements of Jx(.,.) to Jac(i,j). For example, this is how you assign J1 to Jac leftmost upper block:

DO i = 1, 38
   DO j = 1, 38
     Jac(i,j) = J1(i,j)
   END DO
 END DO

Upvotes: 1

Related Questions