1

I have an array a = [1, 2, 3, 4];. I want to compare each element of array a with a number and return a new array contains True/False elements in Julia as few steps as possible. I try result = a < 2 and expected array is result = [True, False, False, False] but it's not working. Hope your help

1

1 Answer 1

5

You need to vectorize (broadcast) the comparison operator so it operates on Vectors. You can do this by adding a dot . to your code.

julia> a = [1, 2, 3, 4]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> a .<= 2
4-element BitVector:
 1
 1
 0
 0

Read more about broadcasting here.

Note that Python's numpy will do this for you automatically, but there are cases where an operation might be ambiguous - do you want it to be element wise or a matrix multiplication? So Julia solves this by explicitly broadcasting any operation with the . command.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.