Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an easy way to find index array zeros in Fortran?

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

like image 414
marco Avatar asked May 16 '13 13:05

marco


People also ask

Does Fortran have 0 Index?

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.

Is Fortran 1 indexed?

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.)

How do you access an array in Fortran?

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], ...)

How do you find the minimum value in an array in Fortran?

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.


2 Answers

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.

like image 137
High Performance Mark Avatar answered Oct 20 '22 21:10

High Performance Mark


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.

like image 20
milancurcic Avatar answered Oct 20 '22 22:10

milancurcic