Sameeresque
Sameeresque

Reputation: 2602

Choosing a set of values in an array

The following code

a=1:1:10
collect(a)
a[a.>4]

returns the expected

6-element Array{Int64,1}:
  5
  6
  7
  8
  9
 10

Whereas,

a[(a.>4) & (a.<8)] 

returns

MethodError: no method matching &(::Int64, ::StepRange{Int64,Int64})

How can this be resolved?

Upvotes: 1

Views: 46

Answers (2)

DNF
DNF

Reputation: 12654

Here are two alternative ways of doing it:

julia> a = 1:10

julia> a[4 .< a .< 8]
3-element Array{Int64,1}:
 5
 6
 7

julia> filter(x->4<x<8, a)
3-element Array{Int64,1}:
 5
 6
 7

Oh, and don't use collect.

Upvotes: 0

hckr
hckr

Reputation: 5583

As a.>4 and a.<8 return BitArrays, you need to broadcast & with a dot (.) as well.

julia> a[(a.>4) .& (a.<8)]
3-element Array{Int64,1}:
 5
 6
 7

Upvotes: 4

Related Questions