Reputation: 310
I am trying to use broadcasting to store the value of function into a three-dimensional array. Below I use a simple example to illustrate what I am trying to do.
Let's say we have a function f
that returns a value from three input values and three vectors X
, Y
and Z
that store the input values:
f = (x, y, z)-> x^2+y^2+z^2
X, Y, Z = randn(100), randn(100), randn(100)
To evaluate f
over all possible combinations of the values stored in the three vectors X
, Y
and Z
, and then store the results in a three-dimensional array, we can do as follows:
[f(x,y,z) for x in X, y in Y, z in Z]
However, I want to avoid using for loops and use dot operators or broadcasting instead. So, I write the following:
broadcast(z->f.(X, Y', z), Z)
However, the problem with it is that the result becomes a one-dimensional array of two-dimensional arrays.
Is there an efficient way to evaluate f
over all possible combinations of the values stored in vectors X
, Y
and Z
and put the results in a three dimensional array without using for loops?
I don't want to use for loops because I am considering to put my code on GPUs in the future and it seems that GPU computing does not work well with for loops.
Thanks!
Upvotes: 0
Views: 307
Reputation: 69819
The simplest is to add a third dimension to Z
, e.g.:
f.(X,Y',reshape(Z, 1, 1, 100))
or directly generate data of appropriate dimensions:
X, Y, Z = randn(100), randn(1,100), randn(1,1,100)
f.(X,Y,Z)
Upvotes: 3