Suppose I want to apply a vector-valued function phi
to a vector x
:
phi(x, d) = [x.^i for i=0:d] # vector-valued function
x = rand(7) # vector
y = phi(x, 3) # should be matrix, but isn't
Now y
should be a matrix, but it is an 4-element Array{Array{Float64,1},1}
, i.e. an array of arrays. Actually, I want y
to be a matrix. Is the implementation of phi
wrong? Or how do I convert it?
Thanks!
As you noted, you can concatenate an array of arrays
x
usinghcat(x...)
, but it's usually better to create a matrix to begin with instead. Two ways that you can do it in this case:Using broadcasting:
As long as
x
is a vector, it will broadcast against the row matrix(0:d)'
.You can get the transpose result by transposing
x
instead of the range0:d
.Using a two-dimensional array comprehension:
This will work as long as
x
is iterable. Ifx
is an n-d array, it will be interpreted as if it were flattened first.You can transpose the result by switching the order of the comprehension variables:
Converting
phi
's output to a matrix can be done as follows:or if you prefer the vectors to be rows, a transpose is needed:
Alternatively, you can convert to a matrix within
phi
by defining it:More generally you can also use the splat operator
...
withhcat
:gives a 2-by-3 matrix