Array-valued function

柔情痞子 提交于 2019-12-02 01:31:10

As IRO-bot already mentioned, use module. This will be a very good practice since you are learning a new language. With a module, you will just have to use the module instead of declaring individually the functions. It is also a good practice to not use keywords as variable names (example: result), use something else. I supposed that you understand well the trick of returning allocatable arrays as fonction return value, introduced in fortran 2003.

Your program can look like this, (the functions are contained in the program file instead of in a separate module, the result is the same)

program matrixMul
implicit none
integer, parameter :: ikind=selected_int_kind(18)
integer(kind=ikind), allocatable, dimension(:,:) :: m1, m2, m3
integer :: rows, cols, i, j

    print *, 'Please enter the number of rows the matrix should have: '
    read *, rows

    print *, 'Please enter the number of columns the matrix should have: '
    read *, cols

    !allocate sufficient memory
    allocate(m1(rows, cols), m2(cols, rows))

    !fill matrixes with numbers entered by the user
    call fillMatrix(m1, rows, cols)
    call fillMatrix(m2, cols, rows)
    m1 = 1
    m2 = 1

    m3 = mulMatrix(m1, m2, rows, cols)

    !prints the result matrix to the screen
    call printMatrix(m3, rows, cols)

    !deallocate memory
    deallocate(m1, m2, m3)

contains
    function mulMatrix(m1, m2, r, c) result(mulMat)
    implicit none
            integer, parameter :: ikind=selected_int_kind(18)
            integer(kind=ikind), dimension(r, c) :: m1
            integer(kind=ikind), dimension(c, r) :: m2
            integer(kind=ikind), allocatable, dimension(:,:) :: mulMat
            integer r, c, i, j, k

            allocate(mulMat(r,r))

            !code which performs calculation is omitted

    end function mulMatrix
end program matrixMul

Another think is: if you are performing the matrix multiplication as defined in linear algebra, the resulting matrix will be rows x rows, see the call to print the result. A caviar will be to not add the size of the matrices as parameters (see M. S. B. comment) and use the intrincsic function LBOUND and UBOUND or SIZE to get them in the function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!