How to convert an array of array into a matrix?

2019-03-24 03:16发布

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!

标签: julia
3条回答
做自己的国王
2楼-- · 2019-03-24 03:49

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:

  1. 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.

  2. 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]
    
查看更多
男人必须洒脱
3楼-- · 2019-03-24 04:03

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]...)
查看更多
别忘想泡老子
4楼-- · 2019-03-24 04:13

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
查看更多
登录 后发表回答