在数组 fortran 中查找非零元素的索引



>我有以下数组

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

我想找到非零元素的索引,并将它们存储在另一个数组或单个变量中以备将来使用。 我不确定如何做到这一点,因为我不知道先验有多少元素是非零的。我正在考虑使用与count(my_array/=0(和maxloc结合使用的循环。

某种循环是唯一的方法吗?我想不出使用 WHERE 或 FINDLOC 的好方法。

我试过这个

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

但是只创建一个没有零元素的新数组,所以我丢失了原始索引。

我不是 100% 确定我理解你想要什么,但这能做到吗?

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

最新更新