Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements from array in Julia matching predicate?

Tags:

arrays

julia

Julia appears to have a lot of Matlab like features. I'd like to select from an array using a predicate. In Matlab I can do this like:

>> a = 2:7 ; >> a > 4  ans =       0     0     0     1     1     1  >> a(a>4)  ans =       5     6     7 

I found a kind of clunky seeming way to do part of this in Julia:

julia> a = 2:7 2:7  julia> [int(x > 3) for x in a] 6-element Array{Any,1}:  0  0  1  1  1  1 

(Using what wikipedia calls list comprehension). I haven't figured out how to apply a set like this to select with in Julia, but may be barking up the wrong tree. How would one do a predicate selection from an array in Julia?

like image 441
Peeter Joot Avatar asked Jan 11 '15 06:01

Peeter Joot


People also ask

How do you access an element in an array Julia?

In Julia, to access the contents/particular element of an array, you need to write the name of the array with the element number in square bracket. Now let us access the elements of 2-D.

How do you use vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do you create an array of zeros in Julia?

This is usually called with the syntax Type[] . Element values can be specified using Type[a,b,c,...] . zeros([T=Float64,] dims::Tuple) zeros([T=Float64,] dims...) Create an Array , with element type T , of all zeros with size specified by dims .


1 Answers

You can use a very Matlab-like syntax if you use a dot . for elementwise comparison:

julia> a = 2:7 2:7  julia> a .> 4 6-element BitArray{1}:  false  false  false   true   true   true  julia> a[a .> 4] 3-element Array{Int32,1}:  5  6  7 

Alternatively, you can call filter if you want a more functional predicate approach:

julia> filter(x -> x > 4, a) 3-element Array{Int32,1}:  5  6  7 
like image 120
DSM Avatar answered Oct 18 '22 19:10

DSM