What is a mask? What is its syntax?

Ultimate newbie question here. I keep seeing MASK as an argument name in intrinsics, and some examples, but I for the life of me cannot find a standalone explanation of how masks work. The closest I get for googling it is this IBM page, which redirects to “Product version no longer published”. I apologize if this has been asked before - I’ve tried to look for this directly.

I understand it’s an expression involving arrays, that’s about it.

For a little context, I have a large if statement like if (i == SOME_CONSTANT .or. i == SOME_OTHER_CONSTANT) (there’s about 20 or so checks). I’ve heard of the any intrinsic and I think the code could be replaced with if (any(my_array_of_constants)) but I don’t know how to write the expression I want.

1 Like

Here is an example:

implicit none

real:: a(5), b
a=[real:: 1, 2.3, 3.4, 6.0, 0.0]

print*, 'array a:', a

b = minval(a, mask= a > 0 )
print*, b  ! ans=1; if mask in not there then minval is 0. 

b = sum(a, mask= a > 1 )
print*, b ! ans: 11.70; sum of 2.3, 3.4, 6.0 
end

output:

gfortran -o test_mask.x test_mask.f90 && ./test_mask.x
 array a:   1.00000000       2.29999995       3.40000010       6.00000000       0.00000000
   1.00000000
   11.6999998

bests!

1 Like

I appreciate the examples. I have some clarifying questions:

What exactly does the expression a > 0 produce? Does it produce [.true., .true., .true., .true., .false.]? Is this something fancy with function application like elemental functions, or is it just generic syntax that is convenient to use here? In what ways can you mix scalars and arrays? What about having two arrays?

1 Like

Yes, it produces what you wrote. You can use comparison operators between

    • two scalars, producing a scalar
    • between an array and a scalar, giving a logical array of the same shape as the array
    • or between two arrays of the same shape, giving a logical array of their common shape.
2 Likes

So a mask isn’t anything fancy, just a common parameter name. Thanks!

1 Like

Yu wrote: but I for the life of me cannot find a standalone explanation of how masks work.

Fortran 90/95 Programming Manual (upc.edu)
https://www-eio.upc.edu/lceio/manuals/Fortran95-manual.pdf

Thanks for the reply. I think the issue is not that no sources explain masks, it’s that none of them call array operations masks, which confused me when I would read about “the mask”. I’d also read information like

The elemental function merge (3) selects values from two arrays or scalars according to a logical mask.

And assume that “a logical mask” was a “thing” in Fortran. A first-class concept. But since it’s really nothing special, a “standalone” expression makes no sense. This link, for example, does not contain the word mask (insofar as Ctrl + F can detect).

1 Like