Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search for odd indices using the section method

I need help.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

Assuming you’re only interested in the array you have given (and not a general array), 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 you’re interested in selecting the odd values from an arbitrary input, 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading