How to find minimum of each column in Fortran and sum op all elements of that column?

118 Views Asked by At

I have a 300x178 matrix and I want to find the minimum of each column of that matrix (1x178). Then I want that, on the location/pixel of the minimum value in each column, the sum is taken from all other pixels in that column. How can I do this using Fortran? Thanks!

Example:

1 4 6 3
2 6 7 4
5 1 5 7

becomes:

1 0 0 1
0 0 0 0
0 1 1 0

and eventually:

8  0  0 14
0  0  0 0
0 11 18 0
1

There are 1 best solutions below

0
lastchance On

As @High Performance Mark has noted, the result is ambiguous if a column has more than one minimum - do you take the first, share them out, ... ?

If you take the first minimum then try the following.

module filter
   implicit none
contains
   function condenseColumns( A ) result( B )
      integer, intent(in) :: A(:,:)
      integer, allocatable :: B(:,:)
      integer c

      allocate( B, mold = A )
      B = 0
      do c = 1, size(A,2)
         B( minloc( A(:,c), 1 ), c ) = sum( A(:,c) )
      end do

   end function condenseColumns

   subroutine writeMatrix( A )
      integer, intent(in) :: A(:,:)
      integer r

      do r = 1, size( A, 1 )
         write( *, "( *( 1x, i3 ) )" ) A(r,:)
      end do

   end subroutine writematrix

end module filter


program matrix
   use filter, only: condenseColumns, writeMatrix
   implicit none
   integer :: A(3,4) = transpose( reshape( [ 1, 4, 6, 3, 2, 6, 7, 4, 5, 1, 5, 7 ], [ 4, 3 ] ) )
   integer, allocatable :: B(:,:)
   
   B = condenseColumns( A )
   call writeMatrix( A );   write( *, * );   call writeMatrix( B )

end program matrix
   1   4   6   3
   2   6   7   4
   5   1   5   7

   8   0   0  14
   0   0   0   0
   0  11  18   0