1

I am trying to write a function which has a scalar input but an array output.

My example is:

Ts(theta) = reshape((/ dcos(theta)**2.d0, dsin(theta)**2.d0, -dsin(2.d0*theta)/2.d0,  & 
    dsin(theta)**2.d0, dcos(theta)**2.d0, dsin(2.d0*theta)/2.d0, &
    dsin(2.d0*theta), -dsin(2.d0*theta), dcos(2.d0*theta) /), (/3,3/))

The Ts(theta) is read as a 1 dimensional array but I want an output as a 2 dimensional array.

Is this possible?

1 Answer 1

4

Of course

function Ts(theta)
  real(rp) :: Ts(3,3)
  real(rp),intent(in) :: theta

  Ts = reshape((/ cos(theta)**2, sin(theta)**2, -sin(2*theta)/2,  &
      sin(theta)**2, cos(theta)**2, sin(2*theta)/2, &
      sin(2*theta), -sin(2*theta), cos(2*theta) /), (/3,3/))
end function

where rp is the right kind constant for current real precision.

Remark: do not use specific functions as dsin and dcos, they are remnants of FORTRAN 66 and obsolete since FORTRAN 77.

Your syntax Ts(theta) = means you probably tried a statement function. They are obsolete also. I am not sure if they can be array-valued, you may try it.

Sign up to request clarification or add additional context in comments.

5 Comments

Statement functions cannot be arrays, you have to use declared functions.
@KyleKanos I am new to fortran, what's the difference between Statement functions and declared functions?
I tried the following unsuccessfully:program test2 implicit none real(rp) :: Ts(3,3) print*, Ts(acos(0.d0)) end program test2 function Ts(theta) implicit none real(rp), intent(in) :: theta real(rp) :: Ts(3,3) Ts = reshape((/ cos(theta)**2.d0, sin(theta)**2.d0, -sin(2.d0*theta)/2.d0, & sin(theta)**2.d0, cos(theta)**2.d0, sin(2.d0*theta)/2.d0, & sin(2.d0*theta), -sin(2.d0*theta), cos(2.d0*theta) /), (/3,3/)) END function
First, you have to place the function into a module or as an internal procedure to the contains section of the program. Second, you have to define rp if you want to use it. Say, integer,parameter :: rp = kind(1.d0)
@VladimirF Thanks, I got it to work. I struggled with this problem for a long time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.