Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of array into a matrix?

Tags:

julia

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!

like image 383
Harmeling Avatar asked Oct 31 '14 11:10

Harmeling


People also ask

Is an array of arrays A matrix?

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.

How do I convert a matrix to an array in R?

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.


1 Answers

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] 
like image 160
Toivo Henningsson Avatar answered Sep 25 '22 22:09

Toivo Henningsson