Mar 28, 2013

Elemental Function and Array Valued Function in FORTRAN

Today, I "discovered" two features of FORTRAN for dealing with arrays.

It has been said arrays are the first class members in FORTRAN. Let v be an array. You can do
sin(v), which returns an array [sin(v(1)), sin(v(2)), ... ]

In order to enable the feature for user defined functions, there are two ways.
1. assign elemental attribute to a function;
elemental real function f(x)

implicit none

  real, intent(in) :: x

  f = x*x + sqrt(abs(x))/2. + 3./x;

end function


Now one can call f with array argument

2. use array valued function

real function f(x)

 implicit none

   real, intent(in) :: x(:);

   real :: f(size(x));

   f = x*x + sqrt(abs(x))/2. + 3./x;

 end function

No comments:

Post a Comment