Defining an Function Returning an Array

I have the following code:

    Program function_as_an_array
    implicit none
    integer:: i
    integer, parameter:: N=10
    real*8:: x(N),y(N),f(N)

    do i=1,N
      x(i)=float(i)
    end do

    call func(f,N,x)

    open(unit=20, file='test.dat')
    do i=1,N
      y(i)=f(i)
      write(20,*) x(i),y(i) 
    end do
    close(20)
    Stop 
    End Program function_as_an_array


    Subroutine func(f,N,x)
    implicit none
    integer i,N
    real*8:: x(N),f(N) 

    do i=1,N
       f(i)=x(i)**2
    end do

    end Subroutine func

I want the program to really be designed for "function as a arrray", i.e. I would like to replace Subroutine funcwith a function fand get the same result (in the main program I want to save a type instruction y=f(x,N)). How can i do this?

Thank.

+4
source share
2 answers

, : , , ( contain ed ), : ( , : , )

module functions
contains

    function func(N,x)
    implicit none
    integer, intent(in) :: N
    double precision, intent(in) :: x(N)
    double precision, dimension(N) :: func

    integer :: i

    do i=1,N
       func(i)=x(i)**2
    end do

end function func

end module functions

Program function_as_an_array
use functions
implicit none
integer:: i
integer, parameter:: N=10
double precision:: x(N),y(N)

do i=1,N
  x(i)=float(i)
end do

y = func(N,x)

open(unit=20, file='test.dat')
do i=1,N
  write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array

, - - Fortran elemental, , Fortran :

module functions
contains

    elemental double precision function f(x)
    implicit none
    double precision, intent(in) :: x

    f = x**2

    end function f

end module functions

Program function_as_an_array
    use functions
    implicit none
    integer:: i
    integer, parameter:: N=10
    double precision:: x(N),y(N)

    do i=1,N
      x(i)=float(i)
    end do

    y = f(x)

    open(unit=20, file='test.dat')
    do i=1,N
      write(20,*) x(i),y(i)
    end do
    close(20)
    Stop
End Program function_as_an_array

, . , , , .

+8

:

Program function_as_an_array
implicit none
integer:: i
integer, parameter:: N=10
real*8 :: x(N),y(N),f(N)
interface func
  function func(x,N) result(f)
    implicit none
    integer N
    real*8:: x(N),f(N) 
  end function
end interface

do i=1,N
  x(i)=float(i)
end do

f = func(x,N)

open(unit=20, file='test.dat')
do i=1,N
  y(i)=f(i)
  write(20,*) x(i),y(i) 
end do
close(20)
Stop 
End Program function_as_an_array


function func(x,N) result(f)
implicit none
integer i, N
real*8:: x(N),f(N) 

do i=1,N
   f(i)=x(i)**2
end do

end function

:

  • result [edit] func real*8:: func(N). . .
  • ( , , . )

.

+2

All Articles