1

I'm trying to write a subroutine to reverse the rows of an array. The following works, but explicitly declares the type of its input arr. Thus I'd need a separate subroutine to do the same thing for an array of type real. Surely there's a way to make it accept an array of arbitrary type - could someone help me with the syntax? Thanks!

SUBROUTINE flipud(arr)

    integer, dimension(:,:), intent(inout) :: arr
    integer, dimension(:,:), allocatable :: tmp
    integer i, j, nrow, ncol, ierr

    nrow = size(arr, 1)
    ncol = size(arr, 2)

    allocate(tmp(nrow, ncol), STAT=ierr)

    tmp(:,:) = arr(nrow:1:-1, :)
    arr = tmp
    deallocate(tmp)

END SUBROUTINE flipud
6
  • 5
    I would just use the expression arr = arr(nrow:1:-1, :) Commented Dec 22, 2014 at 19:19
  • Agreed. Why introduce an extra layer of abstraction for such a simple task. Commented Dec 22, 2014 at 20:58
  • @VladimirF , point taken. You can probably tell Fortran isn't my strong suit. I was actually doing it that way and it wasn't working and I wondered if the syntax didn't work the way I thought it did. (This is actually part of a larger problem in which I'm parsing an ascii file but it's ending up upside down or transposed or something and I'm trying to debug; that must have been caused by a different problem...) Anyway, thanks; I've made the change. Commented Dec 22, 2014 at 22:55
  • If you're reading the elements of an array one at a time don't be surprised if Fortran fills the array column-by-column rather than row-by-row. And perhaps next time ask a question about what your problem really is, rather than about fixing a solution to it. Commented Dec 22, 2014 at 23:28
  • To everyone who responded: thanks for the advice. Commented Dec 23, 2014 at 21:59

1 Answer 1

1

Fortran does not have the equivalent of C++ templates. You can create an interface with module procedures, as sketched below. The code that is common to both subroutines could be placed in a file that is incorporated using the INCLUDE statement.

module foo
interface fliupud
   module procedure flipud_i,flipud_r
end interface flipud

contains
subroutine flipud_i(arr)
integer, dimension(:,:), intent(inout) :: arr
! body
end subroutine flipud_i
!
subroutine flipud_r(arr)
real, dimension(:,:), intent(inout) :: arr
! body
end subroutine flipud_r
end module foo
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but why ? And what would you suggest for body that @VladimirF's comment above doesn't already encompass ?

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.