使用pack函数输出数组中满足条件元素的索引+数组索引

program main_test

    implicit none
   
    real, dimension(5) :: arr1, arr2
    LOGICAL, dimension(5) :: ad, ab, ac, tot
    INTEGER , dimension(:), allocatable:: arr3
    INTEGER :: i
    arr1 = [1.0,2.3,-0.5,3.3,-1.6]
    arr2 = [1.0,-5.3,-0.5,-3.0,-1.6]
    ab = arr1 < 4
    ad = arr1 > 2
    ac = arr2 < 0
   
    tot = ad .and. ab .and. ac
    allocate(arr3(size(tot)))
    arr3 = pack([(i,i=1,5)],tot)
    print *, tot, 'size(tot)=', size(tot)
    print *, 'indices:', arr3
    print *, 'size:', size(arr3)
end program main_test

输出结果:

F T F T F size(tot)= 5
indices: 2 4
size: 2

动态数组会根据实际传递的数组大小调整动态数组大小。但是当声明静态数组arr3数组的大小为5的话,indices的输出结果会是这样的:

indices:           2           4         160           0  1211325946

后面3个数字应该是空的数组自动生成的元素。

数组索引

二维数组示例:

program main_test

    implicit none
   
    real, dimension(5,3) :: arr1
    INTEGER :: arr2(2), arr3(3)
    real, dimension(:,:), allocatable :: newArr
    INTEGER :: i
    allocate(newArr(5,3))
    arr1 = reshape([1.0, 2.3, -0.5, &
                    3.3, -1.6, 2.0, &
                    1.5, 1.3, 1.8, &
                    5.2, 5.8, 5.4, &
                    -1.5, 6.9, 8.1], shape(arr1))
    arr2 = [1,4]
    arr3 = [1,2,3]

    newArr = arr1(arr2,arr3)
    do i=1,5
        if (i<3) then
            print *, newArr(i,:)
        end if
        print *, arr1(i,:)
    end do
    print *, 'size:', size(newArr,1), size(newArr,2)
end program main_test

输出结果:

1.00000000       2.00000000       5.80000019    
   1.00000000       2.00000000       5.80000019
   3.29999995       1.79999995       6.90000010    
   2.29999995       1.50000000       5.40000010
 -0.500000000       1.29999995      -1.50000000
   3.29999995       1.79999995       6.90000010
  -1.60000002       5.19999981       8.10000038
 size:           2           3

 

posted @ 2023-12-27 11:43  搬砖的鹏  阅读(8)  评论(0编辑  收藏  举报