I am just getting started with Fortran and I want to write a simple function which takes three real numbers as arguments and returns a vector containing 3 real numbers, but I have difficulties with the Fortran syntax:
function foo(x,y,z) result(res)
real, intent(in) :: x,y,z
real, intent(out) :: res(3)
res=[x**x,y**y,z**z]
end function foo
program function_test
implicit none
real :: res(3) !declare the array res
real :: foo(3) !declare the return type of the function foo
res=foo(1.0,1.0,1.0) !call foo and save the resulting vector in res
print *,"1st component:",res(1) !Print the first element of the result array
print *,"2nd component:",res(2) !Print the second element of the result array
print *,"3rd component:",res(3) !Print the third element of the result array
end program function_test
Compiling the above code with gfortran results in an error message Error: Rank mismatch in array reference at (1) (3/1)
. Now I understand that the statement res=foo(1.0,1.0,1.0)
seems to be interpreted as "take the element [1,1,1] of the three dimensional array foo" which is of course incorrect, but how can I call foo
and store the resulting array in res
?
(As far as I understand, the line real :: foo(3)
in function_test
is necessary to define the return type of foo
).