Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating combination with vectorized function in Julia

Tags:

julia

In Julia, vectorized function with dot . is used for element-wise manipulation.

Running f.(x) means f(x[1]), f(x[2]),... are sequentially executed

However, suppose I have a function which takes two arguments, say g(x,y)

I want g(x[1],y[1]),g(x[2],y[1]), g(x[3],y[1]), ..., g(x[1],y[2]), g(x[2],y[2]), g(x[3],y[2]), ...

Is there any way to evaluate all combination of x and y?

like image 453
sholi Avatar asked Mar 16 '17 16:03

sholi


2 Answers

Matt's answer is good, but I'd like to provide an alternative using an array comprehension:

julia> x = 1:5
       y = 10:10:50
       [i + j for i in x, j in y]
5×5 Array{Int64,2}:
 11  21  31  41  51
 12  22  32  42  52
 13  23  33  43  53
 14  24  34  44  54
 15  25  35  45  55

In my opinion the array comprehension can often be more readable and more flexible than broadcast and reshape.

like image 103
Fengyang Wang Avatar answered Oct 09 '22 10:10

Fengyang Wang


Yes, reshape y such that it is orthogonal to x. The . vectorization uses broadcast to do its work. I imagine this as "extruding" singleton dimensions across all the other dimensions.

That means that for vectors x and y, you can evaluate the product of all combinations of x and y simply by reshaping one of them:

julia> x = 1:5
       y = 10:10:50
       (+).(x, reshape(y, 1, length(y)))
5×5 Array{Int64,2}:
 11  21  31  41  51
 12  22  32  42  52
 13  23  33  43  53
 14  24  34  44  54
 15  25  35  45  55

Note that the shape of the array matches the orientation of the arguments; x spans the rows and y spans the columns since it was transposed to a single-row matrix.

like image 44
mbauman Avatar answered Oct 09 '22 10:10

mbauman