# Function returning an array

• Defining functions that return an array

• Functions in Fortran 90 can return an array !

• Furthermore, the shape and size of the result array returned by the function is determined at run time

E.g., shape and size of the array can be derived using values from the input parameters

• Syntax to define a function that returns an array:

 ``` FUNCTION MyFuncName(Param1, Param2, ...) RESULT( resultName ) IMPLICIT NONE TYPE, DIMENSION(...) :: resultName TYPE [, Intention] :: Param1 TYPE [, Intention] :: Param2 .... END ! Ends subroutine definition NOTE: You can use input parameters in the result array declaration !!! NOTE: You can function name instead of a result variable ```

• Function that returns an array (Matrix-vector multiplication)

• Problem statement:

 Write a function MatVecMult(A, v) that multiply a matrix A and a vector v and returns a resulting vector The function MatVecMult(A, v) must work for arbitrary size matrices and vectors

• Initial Attempt:

 ``` FUNCTION MatVecMult(A, v) RESULT( w ) IMPLICIT NONE REAL, dimension(:,:), intent(in) :: A REAL, dimension(:), intent(in) :: v REAL, DIMENSION( ??? ) :: w .... END ```

Problem:

 WHAT do we used as size for the returned array ???

Specifically:

 The size of the array returned by the function depends on the size of input matrix and vector !! Specifically, the size of the result vector is equal to the number of rows of input matrix !!

Solution:

 ``` FUNCTION MatVecMult(A, v) RESULT( w ) IMPLICIT NONE REAL, dimension(:,:), intent(in) :: A REAL, dimension(:), intent(in) :: v REAL, DIMENSION( SIZE(A,1) ) :: w .... END ```

The rest is straight forward....

• Example: matrix-vector multiplication function

 ``` function MatVecMult(A, v) result (w) implicit none real, dimension(:,:), intent(in) :: A real, dimension(:), intent(in) :: v real, dimension( SIZE(A,1) ) :: w integer :: i, j integer :: N N = size(v) w = 0.0 !! clear whole vector DO i = 1, N w = w + v(i) * A( :, i ) END DO end function ```

• We cannot do any examples yet...

We must learn how to declare a function that returns an array

• Declaring a function that returns an array

• The interface to declare a function that returns an array must also specify the return type precisely

• Example: declaring the Matrix-vector multiply function

 ``` interface !! Declare MatVecMult function function MatVecMult(A, v) result (w) real, dimension(:,:), intent(in) :: A real, dimension(:), intent(in) :: v real, dimension( SIZE(A,1) ) :: w end function end interface ```

• Now we can show the entire program:

 ``` program Main implicit none interface !! Declare function function MatVecMult(A, v) result (w) real, dimension(:,:), intent(in) :: A real, dimension(:), intent(in) :: v real, dimension( SIZE(A,1) ) :: w end function end interface real, dimension( 3, 3 ) :: A real, dimension( 3 ) :: v1, v2 v2 = MatVecMult(A, v1) !! Use it... ```

• Example Program: (Demo above code)