You can use the find()
function (or the .==
syntax) to accomplish this. E.g.:
julia> x = collect(1:4)
4-element Array{Int64,1}:
1
2
3
4
julia> y = x[find(x%2.==0)]
2-element Array{Int64,1}:
2
4
julia> y = x[x%2.==0] ## more concise and slightly quicker
2-element Array{Int64,1}:
2
4
Note the .==
syntax for the element-wise operation. Also, note that find()
returns the indices that match the criteria. In this case, the indices matching the criteria are the same as the array elements that match the criteria. For the more general case though, we want to put the find()
function in brackets to denote that we are using it to select indices from the original array x
.
Update: Good point @Lutfullah Tomak about the filter()
function. I believe though that find()
can be quicker and more memory efficient. (though I understand that anonymous functions are supposed to get better in version 0.5 so perhaps this might change?) At least in my trial, I got:
x = collect(1:100000000);
@time y1 = filter(x->x%2==0,x);
# 9.526485 seconds (100.00 M allocations: 1.554 GB, 2.76% gc time)
@time y2 = x[find(x%2.==0)];
# 3.187476 seconds (48.85 k allocations: 1.504 GB, 4.89% gc time)
@time y3 = x[x%2.==0];
# 2.570451 seconds (57.98 k allocations: 1.131 GB, 4.17% gc time)
Update2: Good points in comments to this post that x[x%2.==0]
is faster than x[find(x%2.==0)]
.
find
from the performance perspective. Depending on your design considerations, you could code your own efficient routine forx % 2 == 0
or just use Julia's eminently readablefilter
orfind
functions as people have described below. – Jacky==
to index this way, not.==
. I'm not sure which answer to pick, they're all right in different ways and very useful. – Jephthah