0

I have the following array

integer, dimension(4) :: my_array = (/160,0,230,0/)

I would like to find the indices of the elements that are non-zero and store them in another array or individual variables for future use. I am not sure how to do this because I don't know a prior how many elements are non-zero. I was thinking of using a loop combined with count(my_array/=0) and maxloc.

Is some sort of loop the only way? I can't think of a good way to use WHERE or FINDLOC.

I have tried this

ii = COUNT(my_array.NE.0)
ALLOCATE(choices(ii))
choices = PACK(my_array,my_array.NE.0)

But only makes a new array without zero elements, so I lose the original indices.

0

1 Answer 1

1

I'm not 100% sure I understand what you want, but does this do it?

ian@eris:~/work/stack$ cat pack.f90
Program pack_index

  Implicit None

  Integer, Dimension( 1:4 )              :: my_array = [ 160, 0, 230, 0 ]
  Integer, Dimension(  :  ), Allocatable :: choices
  Integer, Dimension(  :  ), Allocatable :: indices

  Integer :: i

  indices = Merge( 0, [ ( i, i = 1, Size( my_array ) ) ], my_array == 0 )
  choices = Pack( indices, indices /= 0 )
  Write( *, * ) choices

End Program pack_index
ian@eris:~/work/stack$ gfortran-8 -std=f2008 -fcheck=all pack.f90 
ian@eris:~/work/stack$ ./a.out
           1           3
4
  • Thanks Ian, yes that's the result I want, but I am in ifort so I think I have to allocate explicitly, it seems in f2008 you don't have to do that? Is there any reason to make indeces allocatable? It seems it should always be the same size as my_array. Jun 5, 2020 at 13:40
  • Standard f2008 does not require you to allocate. From memory the Intel compiler requires an extra flag to get what the standard requires, though as I don't use the intel compiler that often I'm not sure off the top of my head what that option is - or even if what I am remembering is actually history and not true any more
    – Ian Bush
    Jun 5, 2020 at 13:49
  • 1
    Hmmm, maybe you need -standard-semantics on the compiler line
    – Ian Bush
    Jun 5, 2020 at 13:52
  • 2
    ifort only before 17.0.1 requires an option, such as -assume realloc-lhs, included under -standard-semantics. Jun 5, 2020 at 14:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.