Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array or set of conditional evaluation with julia

I am new with Julia. I was wandering if it is possible to write in a single line an if statement in an array or a set in Julia.

For example in python I can write a list such as

s = [1 if np.random.uniform() < 0.5 else 0 for i in range(10)]

which in Julia, if I'm right, should be an array like this

s = []
for i in 0:10
  if rand()<0.5
    push!(s, 1)
  else
    push!(s, 0)
  end
end 

I know I can write the for cycle in a single line i.e.

s =[1 for i in 1:10]

But what about the if..else statement?

like image 640
mic tiz Avatar asked Oct 26 '25 07:10

mic tiz


2 Answers

as @Guido suggested, you can use list comprehension just like python, more specifically:

s = [if rand() < 0.5 1 else 0 end for i in 1:10]

note that julia's if-else statement needs an end. i think this is the same as using map:

map(x -> rand() < 0.5 ? 1 : 0, 1:10)
like image 90
Gnimuc Avatar answered Oct 27 '25 19:10

Gnimuc


To specifically do,

s = [1 if np.random.uniform() < 0.5 else 0 for i in range(10)]

In Julia you can write,

 s = [rand()<0.5?1:0 for i=1:10]
like image 20
Silpara Avatar answered Oct 27 '25 19:10

Silpara