Multiplication of Matrices in Fortran

Asked

Viewed 81 times

1

I am encountering a problem to compile a program in Fortran. The build error accuses that the Shape of the matrices are not compliant. However, I understand that it is mathematically allowed to multiply a 2x3 Matrix by a 3x2 matrix2.

mtx1 = | 2 4 1 |      mtx2 = | 3 4 |    Resultado esperado: | 12  18 |
       | 1 3 6 |             | 1 1 |                        | 15  25 |
                             | 2 3 |

This is the build error message:

print*, mtx1*mtx2 1 2 Error: Shapes for operands at (1) and (2) are not conformable


source code

program test
integer :: mtx1(2,3) = reshape((/2,4,1, 1,3,6/),(/2,3/))
integer :: mtx2(3,2) = reshape((/3,4, 1,1, 2,3/),(/3,2/))

print*, mtx1*mtx2

end program teste
  • 1

    Hans, could you put your question in English?

  • I tried to use intrinsic function matmul(mtx1,mtx2), compiled, however result is not consistent.

  • 1

    Use the [Edit button]

2 answers

2

The Fortran language does not multiply multidimensional matrices directly, only vectors (one-dimensional).

To multiply multidimensional matrices, use the function matmul (Fortran 90):

program test

  integer :: mtx1(2,3) = reshape((/2,4,1, 1,3,6/),(/2,3/))
  integer :: mtx2(3,2) = reshape((/3,4, 1,1, 2,3/),(/3,2/))

  ! -----
  ! Aqui: trocar pela funcao matmul
  ! -----
  print*, matmul(mtx1, mtx2)

end program test

After execution, the multiplication result is printed correctly:

13          22          13          24
  • I was expecting the results line 1 : 12 15 line 2: 18 25

  • I’ll try a na approach using the column-major statement in the matrix constructor.

  • the result 13 22 13 24 is not what I expected as the correct answer of the multiplication of the two matrices

  • 1

    The original question was about the non-compliance of shapes of the matrices and not on the expected result. But after editing the question and the example you put, yes, it’s correct, because the data needs to be in the format column-major.

1


The Fortran language uses the model column-major to store the contents of a array contiguously in memory. Therefore, it is necessary to keep this in mind when assigning values in the constructor of a variable of type array (dimension); Further considering this and the response of @Gumball (use the function matmul for amultiplicar matrices in Fortran), the program with the correct result can be the one of the following source code:

    program test
    
      integer :: mtx1(2,3) = reshape((/2,1, 4,3, 1,6/),(/2,3/)) !column-major
      integer :: mtx2(3,2) = reshape((/3,1,2 ,4,1,3/),(/3,2/))
    
      print ('(" | ",i2,2x,i2," | ")'), matmul(mtx1,mtx2)
    
    end program test

Producing the desired result:

| 12  18 |                                                                                      
| 15  25 |

Browser other questions tagged

You are not signed in. Login or sign up in order to post.