How to intersect a Cartesian Index with a regular index?

For example, I have an Index1 that is generated from this:

A = [NaN, 2.1, NaN, -3, 8, 65, NaN];
f1(A) = [idx for idx in CartesianIndices(A) if @inbounds (isnan(A[idx])) ];
Index1 = f1(A);

Results of Index1:

Index1 = 3-element Vector{CartesianIndex{1}}:

An Index2 generated from:

C = [1 2 3 4 5 6 7]
Index2 = C.>1

So my Index2 is

1×7 BitMatrix:
 0  1  1  1  1  1  1

How do I get their intersect, i.e, the Index of 3 and 7 as a Boolean array of [0, 0,1,0,0,0,1]?

Using InvertedIndices.jl, you could do this with something like:

Ind2[Not(Index1)] .= false

where Ind2 is now the intersection of both.

1 Like

You could also keep the coherency in your code and define in a similar way:

C = [1, 2, 3, 4, 5, 6, 7]
Index2 = [idx for idx in CartesianIndices(C) if @inbounds (C[idx]>1) ]
intersect(Index1, Index2)

2-element Vector{CartesianIndex{1}}:
1 Like

Many thanks for the replies!

For my data processing, I have to do the intersect based on the new Index2 and the inverse of Index1. Unfortunately, even if I generate my Index2 using the same approach, the below code gives me an error:

using InvertedIndices
intersect(Not(Index1), Index2)

Error message:
MethodError: no method matching length(::InvertedIndex{Vector{CartesianIndex{1}}})

I do need my Index1. It was generated through a very complex process. Basically, I need to first process the first batch of data based on Index1, then I need to find matching data from the remaining rows, thus the need for an inverse Index1.

It seems that the Cartesian index is not very user friendly after all. Maybe I should try to figure out how to generate a regular Boolean index in the first place?

Could you use:

ix = CartesianIndices(A).∉ Ref(Index1)

7-element BitVector:
1 Like

That works! Thank you so much.