Checking all elements of array for a logical condition in fortran

4.5k views Asked by At

I want to check all rows of an array for a logical condition. I used function ALL as described in GNU GCC guide https://gcc.gnu.org/onlinedocs/gfortran/ALL.html

Here is a sample code:

program test3
implicit none
real, allocatable, dimension (:,:) :: mat1
integer :: i,j,k,r
logical :: lg
r=3
allocate(mat1(r,r))
mat1=transpose( reshape( (/-1,-2,-3,-4,-5,-6,-7,-8,-9/), (/3,3/)))
lg=all (abs(mat1)<10,1)
write (*,*) lg
end program

In this program, I want to check whether absolute value of all elements along all rows is less than 10. But I am getting error

lg=all (abs(mat1)<10,1)
Error: Incompatible ranks 0 and 1 in assignment

Any idea about this error or how to do this check?

2

There are 2 answers

0
francescalus On BEST ANSWER
Error: Incompatible ranks 0 and 1 in assignment

means that you are trying to assign a rank-1 array to a scalar variable.

In this case lg is your scalar left-hand side. As you want to test the condition against each row (as supported by using the [dim=]1 specifier) it makes sense for lg to be an array of rank-1 with as many elements as there are rows in mat1.

That said, because Fortran uses column-major storage using ALL(...,dim=1) here is actually giving you the test result along columns. In general, the result of ALL(L, dim=n) is of shape [d_1, d_2, ..., d_{n-1}, d_{n+1}, ..., d_m] where the shape of L is [d_1, ..., d_m].

[As noted in another answer the result of ALL(L) is a scalar. If this is what you want here, then I may have something to say about potential confusion with the language of the formal description of ALL.]

2
Andrey On

Use this to get scalar logical:

lg = all(abs(mat1) < 10)