Question

I'm new to Fortran. For now, I'm trying to make a simple function that should print the coefficients of a matrix. Originally I wanted to do something more interesting with the matrix (that's why I used the FUNCTION keyword), but I had to dumb it down, since "Hello world", and "multiply a number by 2" are the only programs I managed to compile so far.

Here is my code:

PROGRAM my_program
    IMPLICIT NONE
    INTEGER, EXTERNAL :: print_coefs
END PROGRAM my_program

FUNCTION print_coefs(arr)
    IMPLICIT NONE
    REAL, INTENT(IN), DIMENSION(:) :: arr
    INTEGER :: print_coefs
    INTEGER :: i,j
    do i = 1, size(arr, 1)
        do j = 1, size(arr, 2)
            print *, arr(i,j)
        enddo
    enddo
    print_coefs = 0
END FUNCTION

So I have this error at compile time:

Error: 'dim' argument of 'size' intrinsic at (1) is not a valid dimension index.

Why? Isn't size the right way to get the dimensions of the matrix?

Thanks for your help.

Était-ce utile?

La solution

The array arr is declared as being of rank 1. So, assuming the compiler is pointing to the line where size(arr,2) is given, this is not valid code: it is asking for the size of the second (non-existent) dimension.

From the rest of the function print_coeffs it appears desirable that arr be declared as rank-2: real, intent(in), dimension(:,:) :: arr.

It should, however, be noted that a function like this (arr is an assumed-shape array) will require an explicit interface for the caller. That is, if you want to call this function eventually from the main program then integer, external :: print_coeffs isn't going to be sufficient. See other questions and answers on SO---such as here---for more details.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top