'Search for odd indices using the section method

I don't understand how I can implement the search for even elements using the section method.

I did a search for odd elements, but I need to find even ones

I need it to output 2 4 6 8, but my program outputs 1 3 5 7 9

program main
  implicit none
  
  integer, DIMENSION(3, 3) :: array = reshape((/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /), shape(array))
  integer                  :: i = 0
  integer, allocatable     :: B(:)
  
  B = [(Array(::2,i), i=1, 3)]
  print *, B
end program main


Solution 1:[1]

If you're interested in the elements with odd indices, you want

B = [(Array(modulo(i,2)+1::2, i), i=1, 3)]

modulo(i,2)+1 is 2 when i is odd, and 1 when i is even. This means that for columns with odd i you select every other element starting at the second element, and for columns with even i you select every other element starting at the first element.

If instead you're interested in selecting the odd values from an arbitrary array, you can't do this with a simple slice, and you instead need a conditional filter. For example,

B = [integer::]
do i=1,3
  do j=1,3
    if (modulo(Array(j,i),2)==0) then
      B = [B, Array(j,i)]
    endif
  enddo
enddo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1