Parsing matrix using Booleans in Julia

So I am trying to select elements from a matrix using booleans, but I stumble upon this behavior I cannot understand. Consider the following matrices.

id = [1 1 2 2]
x1 = [1 2 3 4 ]
x2 = [5 6 7 8 ]
X = transpose([x1 ; x2 ])

Now I want to select all the elements in X that correspond to id==1. This is one way to do it.

X[ [true ,true, false ,false ] , : ]
# 2×2 Matrix{Int64}:
# 1  5
# 2  6

However, when I create the boolean using logical conditions, it fails to produce the desired result.

select_row = isone.(transpose(id).==1) 
X[ select_row , : ]
# 2×1 Matrix{Int64}:
# 1
# 2

Any idea about what is happening? Thank you in advance.

Upvotes: 5

Views: 383

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

First let me comment how to solve your issue. Your select_row selector must be a vector, so the following will work:

julia> select_row = vec(transpose(id).==1)
4-element BitVector:
 1
 1
 0
 0

julia> X[select_row, :]
2×2 Matrix{Int64}:
 1  5
 2  6

In your case select_row is a 4x1 matrix:

julia> select_row = isone.(transpose(id).==1)
4×1 BitMatrix:
 1
 1
 0
 0

in which case we hit a situation that is not well documented in the Julia Manual how this should be handled (I will discuss this case with core team and comment here is there is an official interpretation for it).

Upvotes: 5

Related Questions