# How to check if there are at least one true Cartesian index?

I love Cartesian indices because of its performance. One issue I’m not clear is how to check if there are at least one true Cartesian index.

For example, if I have a vector as the below:
`A = [1, 2, 3, 4, 5];`

My regular Index will work like this:

``````Ind1 = A .>3.5
5-element BitVector:
0
0
0
1
1
``````

By using the below syntax, I can check if there is at least one valid value:

``````if sum(Ind1) > 0
...
end
``````

My question is how do I check whether a group of Cartesian indices have at least one valid value?

Many thanks!

Can you give an example of what you need this for?
In particular, I don’t understand what so you mean by “index” being different than zero. In your example you don’t have a list of indices.

Could you use the findall function and check if the result is empty?

``````julia> A = [1, 2, 3, 4, 5];

julia> findall(>(3.5),A)
2-element Vector{Int64}:
4
5

julia> isempty(findall(>(3.5),A))
false

julia> B = [1 2 ; 3 4]
2×2 Matrix{Int64}:
1  2
3  4

julia> findall(>(3.5),B)
1-element Vector{CartesianIndex{2}}:
CartesianIndex(2, 2)

julia> isempty(findall(>(3.5),B))
false
``````
1 Like

For example, I have a function like the below to check if a column data has at least real value, i.e., non-NaN and non -999 (missing value indicator).

`f(A) = [idx for idx in CartesianIndices(A) if @inbounds (!isnan(A[idx]) && A[idx] != -999)];`

If my column data is as below:
B = [1.0, 2.0, NaN, 5.0, -999.0, 8.0];

`Ind2 = f(B)` would give me these Cartesian indices:
`Ind2 = CartesianIndex{1}[CartesianIndex(1,), CartesianIndex(2,), CartesianIndex(4,), CartesianIndex(6,)]`

`C[Ind2] = [1.0, 2.0, 5.0, 8.0]`

What I’m trying to learn is how to check if Ind2 contains at least one true values.

I think I found the answer:
`isempty(Ind2) = true`. # when there are no true values.

`any(>(3.5),B)` is what you’re looking for

2 Likes

This is also how you should be doing the linear index comparison in the beginning. Why? Because `any` short-circuits. If the first element of `A` is `>0`, only one comparison is needed to definitively say that there is at least one element `>0`. Compare

``````julia> function ispositive(x)
println("\$x > 0? \$(x > 0)")
return x > 0
end;

julia> x = [-1, 1, -2, 2];

julia> sum(ispositive.(x)) > 0
-1 > 0 ? false
1 > 0 ? true
-2 > 0 ? false
2 > 0 ? true
true

julia> any(ispositive, x)
-1 > 0 ? false
1 > 0 ? true
true

julia> all(ispositive, x)
-1 > 0 ? false
false
``````
1 Like