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!
An array is a vector with one or more dimensions. A one-dimensional array can be considered a vector, and an array with two dimensions can be considered a matrix. Behind the scenes, data is stored in a form of an n-dimensional matrix.
Functions Used data-is the input vector which becomes the data elements of the matrix. nrow-is the numbers of rows to be created. ncol-is the numbers of columns to be created. byrow-is a logical clue,if it is true then input vector elements are arranged by row.
As you noted, you can concatenate an array of arrays x
using hcat(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:
phi(x, d) = x.^((0:d)')
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 range 0:d
.
Using a two-dimensional array comprehension:
phi(x, d) = [xi.^di for xi in x, di in 0:d]
This will work as long as x
is iterable. If x
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:
phi(x, d) = [xi.^di for di in 0:d, xi in x]
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