# Index of a grid

My goal is to find the index of a grid that meet certain criteria. For example, I have an X Y that is meshgridded together using the below function:
`X, Y = ndgrid([-180:1:180], [-90:1:90];`

So my Y will be like a matrix like the below:

``````Y = [-90, -89, -88, ... 90;
...
-90, -89, -88, ... 90];
``````

How do I find the Index of the grid with Y>80, so that Y[Index] will give me a grid where Y>80? Why didn’t the below work? It gives me a vector, instead of a matrix.
`Ind = Y .> 80;`

Many thanks!

Can you make an MWE? I don’t think Y is a matrix because:

``````julia> Y = rand(5, 5);

julia> Y .> 0.5
5×5 BitMatrix:
0  1  0  1  1
0  1  1  0  0
0  0  0  1  0
0  1  1  1  0
0  0  0  0  1
``````
2 Likes

Hi there, I tried the following and got a matrix:

``````julia> Y = rand(1:20, 5,5)
5×5 Matrix{Int64}:
6  10   1  10   3
16  11  12   3  11
13  20   1   4   3
1   9   1  12   1
15  13  15   7   6
julia> Y .> 10
5×5 BitMatrix:
0  0  0  0  0
1  1  1  0  1
1  1  0  0  0
0  0  0  1  0
1  1  1  0  0
``````

However, if you want indices in another format, try:

``````julia> findall(Y .> 10)
10-element Vector{CartesianIndex{2}}:
CartesianIndex(2, 1)
CartesianIndex(3, 1)
CartesianIndex(5, 1)
CartesianIndex(2, 2)
CartesianIndex(3, 2)
CartesianIndex(5, 2)
CartesianIndex(2, 3)
CartesianIndex(5, 3)
CartesianIndex(4, 4)
CartesianIndex(2, 5)
``````
1 Like

It’s true that the Index is a matrix, but when you want to get the real values of the Y by doing the below:
`Y[Y .> 0.5]`
it will become a vector.

Unfortunately, I got the same issue:

``````Ind = findall(Y .> 10);
Y_new = Y[Ind];
``````

will give me a vector as well.

if I have this matrix:

``````julia> a = rand(0:1, 3,3)
3×3 Matrix{Int64}:
1  0  0
0  0  1
1  0  0
``````

what is the “grid” you expect/want to get by doing

``````a[a .> 0]
``````

?

2 Likes

Hmm do you want something like a matrix of only the selected terms and everything else zero? If so, then:

``````julia> Ynew = zeros(5,5)
5×5 Matrix{Float64}:
0.0  0.0  0.0  0.0  0.0
0.0  0.0  0.0  0.0  0.0
0.0  0.0  0.0  0.0  0.0
0.0  0.0  0.0  0.0  0.0
0.0  0.0  0.0  0.0  0.0

julia> Ynew[inds] .= Y[inds];

julia> Ynew
5×5 Matrix{Float64}:
0.0   0.0   0.0   0.0   0.0
16.0  11.0  12.0   0.0  11.0
13.0  20.0   0.0   0.0   0.0
0.0   0.0   0.0  12.0   0.0
15.0  13.0  15.0   0.0   0.0
``````

Otherwise, what `Y[inds]` does is return a vector of all the values in `Y` that match your criterion. That is, `inds` is a vector of indices that match your criterion and then you get a vector out of `Y` of those corresponding indices. Does this make sense?

1 Like

Guess I can just do a reshape and get what I want.

Many thanks All.

``````[1 1
1 0]
``````

then why not

``````[1 0
1 1]
``````

if you know exactly what you will get, just do a reshape, but it’s not clear you can always get back a “matrix” without ambiguity

2 Likes