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
?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With