# Equivalent of numpy.where in Fortran

In python:

``````import numpy as np
a=np.array([0, 10, 2, 3, 4, 51, 6, 7, 8, 9])
print (np.where(a<=5)[0])
#output: array([0, 2, 3, 4])
``````

Is there an equivalent of “where” in Fortran?

PACK should work fine for this. A quick google search turned up this example, which should help you out.

1 Like

Thanks for pointing out this.

Here is the example:

``````module mod_mask
implicit none

contains

subroutine where(arr, condition_scalar, indices)
real, intent(in) :: arr(:)
real, intent(in):: condition_scalar
integer, allocatable, intent(out) :: indices(:)

integer:: i, n
n = size(arr, dim=1)
! print*, "arr:", arr
! print*, "condition_scalar", condition_scalar
indices = PACK([(i, i=1,n)], arr > condition_scalar)
! print*, "where:", indices
end subroutine where

implicit none

integer, allocatable :: indices(:)
integer :: i !, n
real, allocatable :: r(:)

r = ([(i*1.1,i=10,15)])
call where(r, 13., indices)
print*, 'input array:', r
print*, 'conditional scalar:', 13.
print*, "indices:", indices
!
! input array:   11.0000000       12.1000004       13.2000008       14.3000002       15.4000006       !16.5000000
! conditional scalar:   13.0000000
! indices:           3           4           5           6
!

``````

According to the NumPy documentation (numpy.where — NumPy v1.25 Manual), NumPy’s `where` is meant for merging entries as in

``````c = np.where(mask,a,b)
``````

where `c` get values assigned from `a` and `b` depending on `mask`.

In Fortran, `merge` (MERGE (The GNU Fortran Compiler)) or `where` (https://www.intel.com/content/www/us/en/docs/fortran-compiler/developer-guide-reference/2023-1/where.html) can be used to achieve this.

My aim is to look for the indices of the input array where index values is <=5. Which numpy.where can do easily.

``````import numpy as np
a=np.array([0, 10, 2, 3, 4, 51, 6, 7, 8, 9])
print (np.where(a<=5)[0])
#output: array([0, 2, 3, 4])
``````

And the same is done by the pack function [as shown in the example above] in Fortran. It seems that merge may not do the same as it selects values from two arrays as shown here merge function.

yes, but the pythonic way of doing this would be

``````import numpy as np
a=np.array([0, 10, 2, 3, 4, 51, 6, 7, 8, 9])
print (np.asarray(a<=5).nonzero()[0])
#output: [0, 2, 3, 4]
``````

so if people search for the equivalent of `np.where`, `merge` or `where` are relevant Fortran functions.

1 Like