Stores the elements of array
in an array of rank one.
The beginning of the resulting array is made up of elements whose mask
equals true
. Afterwards, positions are filled with elements taken from vector
.
Fortran 95 and later
Transformational function
result = pack(array, mask[,vector])
array
- Shall be an array of any type.mask
- Shall be an array of type logical
and of the same size as array
. Alternatively, it may be a logical
scalar.vector
- (Optional) shall be an array of the same type as array
and of rank one. If present, the number of elements in vector
shall be equal to or greater than the number of true elements in mask
. If mask
is scalar, the number of elements in vector
shall be equal to or greater than the number of elements in array
.The result is an array of rank one and the same type as that of array
. If vector
is present, the result size is that of vector
, the number of true
values in mask
otherwise.
Gathering nonzero elements from an array:
program test_pack_1
integer :: m(6)
m = (/ 1, 0, 0, 0, 5, 0 /)
write(*, fmt="(6(i0, ' '))") pack(m, m /= 0) ! "1 5"
end program
Gathering nonzero elements from an array and appending elements from vector
:
program test_pack_2
integer :: m(4)
m = (/ 1, 0, 0, 2 /)
write(*, fmt="(4(i0, ' '))") pack(m, m /= 0, (/ 0, 0, 3, 4 /)) ! "1 2 3 4"
end program