Currently in my code I have a 2D array
integer, allocatable :: elements(:,:)
and define some constants
integer, parameter :: TYP = 1 integer, parameter :: WIDTH = 2 integer, parameter :: HEIGHT = 3 ! ... integer, parameter :: NUM_ENTRIES = 10
and allocate something like
so I can access elements like
write(*,*) elements(WIDTH,100) ! gives the width of the 100th element
Now I would like to have not only integer but a mixture of types for every element.
So I define a derived type
type Element logical active integer type real width ! etc end type
and use an array of Elements
type(Element), allocatable :: elements(:)
With the 2d array version I could call a subroutine telling it which entry to use.
subroutine find_average(entry, avg) integer, intent(in) :: entry real, intent(out) :: avg integer i, real s s = 0 do i = lbound(elements,1), ubound(elements,1) if (elements(TYP,i) .gt. 0) s = s + elements(entry,i) end do avg = s/(ubound(elements,1)-lbound(elements,1)) end subroutine
So I could
call find_average(HEIGHT) to find the average height or pass
WIDTH to get the average width.
(And my subroutines do more advanced things than finding the average height or width, this is just an example.)
Question: How can I use different types (as with the derived type) but also reuse my functions to work with different entries (as in the example subroutine)?