Fortran特有の行列演算の書き方

Fortran90で行列を扱ってみます。配列ではそれぞれの配列要素の演算を簡単な記述で表すことができます。

main.f90

program main
  integer(kind=8), pointer :: matrix(:,:)
  integer(kind=8), parameter :: nele = 3

  allocate(matrix(nele, nele))

  call set_matrix(matrix, nele)
  call print_matrix(matrix, nele)

  write(*,*) "plus 10"
  matrix = matrix + 10
  call print_matrix(matrix, nele)

  write(*,*) "plus matrix"
  call set_matrix(matrix, nele)
  matrix = matrix + matrix
  call print_matrix(matrix, nele)

  write(*,*) "product matrix"
  call set_matrix(matrix, nele)
  matrix = matrix * matrix
  call print_matrix(matrix, nele)

  write(*,*) "division matrix"
  call set_matrix(matrix, nele)
  matrix = matrix / matrix
  call print_matrix(matrix, nele)

  contains

  subroutine set_matrix(mat, n)
    integer(kind=8), intent(inout) :: mat(:,:)
    integer(kind=8), intent(in) :: n

    integer(kind=8) :: l = 1
  
    !allocate(mat(n:n))
  
    do i=1, n
      do j=1, n
        !write(*, fmt='(I4)', advance='no') l
        mat(i, j) = l
        l = l + 1
      enddo
      !print *
    enddo

    l = 1 !< reset

  end subroutine set_matrix
  
  subroutine print_matrix(mat, n)
    integer(kind=8), intent(in) :: mat(:,:)
    integer(kind=8), intent(in) :: n
    do i=1, n
      do j=1, n
        !print '(I5 )', ele
        !write(*, fmt='(I5 )', advance='no'), ele
        write(*, fmt='(I5 )', advance='no'), mat(i, j)
        !write(*, "I5 ") ele
      enddo
        print *
    enddo 
  end subroutine print_matrix

end program main

10を足す場合は
matrix + 10

行列要素同士を足す場合は
matrix + matrix

行列要素同士の掛け算は
matrix * matrix

行列要素同士の割り算は
matrix / matrix

こんな感じです。

C言語ではちゃんとループしないといけないですね。それをFortranでやろうとすると、

do j = 1, jmax
  do i = 1, imax
    matrix(i, j) = matrix(i, j) + matrix(i, j)
  end do
end do

という感じですかね。ちなみに、2次元配列の走査方法がC言語と違うので注意。