I'm searching for intrinsic fortran functions to help me find the array index with zeros, or other value. I only found minloc function, but I think this is not suitable. Is there an matlab find function equivalent in Fortran?
Thanks
C arrays always start at zero, but by default Fortran arrays start at 1. There are two usual ways of approaching indexing. You can use the Fortran default, as in the preceding example.
Array indexing in Fortran is 1-based by default: integer,parameter :: N=8 real(4),dimension(N) :: x do i=1,N ... x(i) ... (Different from most other languages.)
To access an array section, you need to provide the lower and the upper bound of the section, as well as a stride (increment), for all the dimensions. This notation is called a subscript triplet: array ([lower]:[upper][:stride], ...)
8.199 MINVAL — Minimum value of an array Determines the minimum value of the elements in an array value, or, if the DIM argument is supplied, determines the minimum value along each row of the array in the DIM direction. If MASK is present, only the elements for which MASK is . TRUE. are considered.
Given an integer array such as:
testarr = [0,1,0,2,0,3,0,4]
then the expression
pack([(ix,ix=1,size(testarr))],testarr==0)
will return the indices of the elements in testarr
equal to 0
.
I'll leave you to generalise or enhance this to deal with real numbers or to wrap it into a function to suit your purposes.
The Fortran 2008 standard adds a new intrinsic function findloc
which offers to be the replacement for Matlab's find
that the question seeks; the compiler I use most (Intel Fortran 13.1.1) doesn't seem to implement this yet.
Yes, see High Performance Mark's answer on how to do this with with the PACK
instrinsic function.
If I needed to perform operations on all array elements that satisfy some condition, I would implement it using a combination of DO
and IF
constructs, for example:
INTEGER :: i
REAL,DIMENSION(10) :: a
REAL :: eps = someSmallNumber
...
DO i = 1,SIZE(a)
IF( 0 > a(i)-eps .AND. 0 < a(i)+eps )THEN
...
ENDIF
ENDDO
The range (a(i)-eps,a(i)+eps)
is used above to prevent against comparison fail due to floating point arithmetic. If working with integers, an exact ==
comparison will do.
If only assignment operations to array elements are needed, you can achieve this using WHERE
or FORALL
constructs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With