subset array with Fortran given a condition? -
suppose have array a(n,m). possible subset array in fortran create new array? example,
a = 11 22 43 55 15 56 65 63 54 56 32 78
i want create array b m-1 columns , rows satisfies a(:,2) .eq. 56
so b should be:
b = 15 65 63 54 32 78
i don't know how start because, example, dimension of b should determined dynamically (i think)
thanks help!
are looking this?
function extractb(a) result(b) integer, dimension(:,:), intent(in) :: integer, dimension(:,:), pointer :: b integer :: nrowb, i, pos nrowb = count( a(:,2)==56) allocate( b(nrowb, size(a,2)-1 ) ) pos = 1 = 1, size(a,1) if(a(i,2)==56)then b(pos,1) = a(i,1) b(pos,2:) = a(i,3:) pos = pos+1 end if end end function extractb
that call like
b = extractb(a)
with b defined like:
integer, dimension(:,:), allocatable :: b
i assumed integer arrays. if compiler implement pointer return value, can used pointers in place of allocatable.
====adding full program ====
module extract contains subroutine testextract(a, b) double precision, dimension(:,:), intent(in) :: double precision, dimension(:,:), intent(out), allocatable :: b b = extractb(a) end subroutine testextract function extractb(a) result(b) double precision, dimension(:,:), intent(in) :: double precision, dimension(:,:), allocatable :: b integer :: nrowb, i, pos nrowb = count( a(:,2)==56) allocate( b(nrowb, size(a,2)-1 ) ) pos = 1 = 1, size(a,1) if(a(i,2)==56)then b(pos,1) = a(i,1) b(pos,2:) = a(i,3:) pos = pos+1 end if end end function extractb end module extract program test use extract integer, parameter :: n = 3 integer, parameter :: m = 4 double precision, dimension(3,4) :: double precision, dimension(:,:), allocatable :: b a(1,:) = [11, 22, 43, 55] a(2,:) = [15, 56, 65, 63] a(3,:) = [54, 56, 32, 78] print*, 'a :' print*, int(a) !b = extractb(a) call testextract(a, b) print*, 'b' print*, int(b) end program
Comments
Post a Comment