Accessing 2D array/matrix values with Booleans

Take a matrix A and a vector of Booleans , say, booleRand (whose length is the same as the number of columns or rows in A). I want to be able to access entire rows or columns using the Boolean vector. I am a bit surprised that I couldn’t find an answer to this.

I thought it would be something like this (which is how you do it in MATLAB and NumPy).

 A=[1 2 3;4 5 6;7 8 9]
 p=[0.2 0.4  0.3]
booleRand=rand(1,3).>p
A[:, booleRand] # This does NOT work.
p[booleRand] # This does works.

The errors:

ERROR: BoundsError: attempt to access 3×3 Array{Int64,2} at index [Base.Slice(Base.OneTo(3)), Base.LogicalIndex(Bool[true false true])]

Perhaps it has something to do with “true indices”? But what is a true index? Is that using a single index to access a value of a 2/n-D array? ie A[5] which gives 5, just like A[2,2]?

Make p and boolRand vectors instead of matrices and it will work.


julia>  p=[0.2, 0.4 , 0.3]
3-element Array{Float64,1}:
 0.2
 0.4
 0.3

julia> booleRand=rand(3).>p
3-element BitArray{1}:
 true
 true
 true

julia> A[:, booleRand]
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

Right. Subtle. Thanks.

So the lesson here is rand(n) is not the same as (or equivalent to) rand(n,1) (or rand(1,n)).

That’s right, Julia differentiates between vectors and matrices, something matlab mostly doesn’t.

2 Likes