Search code examples
arraysfortranmatrix-multiplication

Data statement for Matrices


I want to use the data statement to initialize matrices in Fortran. In my opinion, one advantage of using this method is that it provides a compact way of initializing matrices. However, the way I used it in the example below resulted in an error in the calculation. Both Z1 and ZZ1 should give a matrix of size 2x1 equal to [7;13] (ZZ1 = [7;13], Z1 = [10;12]). I believe that an option such as order=(/2,1/) should be used, but I have not been able to find it. Can someone help?

program test_Multiplication
  implicit none
  integer :: Xp1(3,1), b1(2,1), IW1_1(2,3), Z1(2,1)
  integer :: XXp1(3,1), bb1(2,1), IIW1_1(2,3), ZZ1(2,1)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  ! with data statement !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  data Xp1(1:3,1) &
  /1, &
   2, &
   3/
  data IW1_1(1:2,1:3) &
  /1, 1, 1, &
   2, 2, 2/
  data b1(1:2,1) &
  /1, &
   1/
  
  Z1 = matmul(IW1_1,Xp1)+b1
  print*, 'Z1', Z1

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  ! without data statement !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  XXp1 = reshape( (/1, &
   2, &
   3 /), &
   shape(XXp1), order=(/2,1/) )
  
  IIW1_1 = reshape( (/ 1, 1, 1, &
   2, 2, 2/), &
   shape(IIW1_1), order=(/2,1/) )
  
  bb1 = reshape( (/1, &
   1/), &
   shape(bb1), order=(/2,1/) )

  ZZ1 = matmul(IIW1_1,XXp1)+bb1
  print*, 'ZZ1', ZZ1

end program test_Multiplication 

Solution

  • @user790082,

    Steve has already given your answer as a comment (Fortran uses column-major order: first index changes fastest in memory). If you must use a data statement then change your initialisation of IW1_1 to

      data IW1_1(1:2,1:3) /1, 2, 1, 2, 1, 2 /
    

    (Line continuations are a considerable distraction in this instance.)