How to convert an array of array into a matrix?
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 range0: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. 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:
phi(x, d) = [xi.^di for di in 0:d, xi in x]
Converting phi
's output to a matrix can be done as follows:
y = hcat(phi(x, 3)...)
or if you prefer the vectors to be rows, a transpose is needed:
y = vcat([x' for x in phi(x, 3)]...)
Alternatively, you can convert to a matrix within phi
by defining it:
phi(x, d) = hcat([x.^i for i=0:d]...)
More generally you can also use the splat operator ...
with hcat
:
X = [[1,2], [3, 4], [5,6]]
hcat(X...)
gives a 2-by-3 matrix
1 3 5
2 4 6
An alternative to splatting like hcat(X...)
is to use reduce
reduce(hcat, X)
So, in your case, this will do the trick
reduce(hcat, phi(x, 3))