Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a matrix to an array of arrays?

In How to convert an array of array into a matrix? we learned how to convert an array of arrays to a matrix. But what about the other way around? How do we go from input to output, as shown below?

input = [1 2 3; 4 5 6; 7 8 9]
output = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 836
catastrophic-failure Avatar asked Jan 14 '18 22:01

catastrophic-failure


People also ask

How do you convert a matrix to an array?

We can use numpy. flatten() function to convert the matrix to an array. It takes all N elements of the matrix placed into a single dimension array.

Is a matrix an array of arrays?

A matrix is a 2D array with which follows the rules for linear algebra. It is, therefore, a subset of more general arrays which may be of higher dimension or not necessarily follow matrix algebra rules.

How do I convert a matrix to an array in C++?

For example using row major versus column major of a 3x2 matrix: one representation in contiguous memory would be { {0,1,2}, {3,4,5} } where these are the indices into a single dimensional array, the other representation in contiguous memory would be { {0,1}, {2,3}, {4,5} } again with the same indices into the 1D array ...


2 Answers

If you want to make a copy of the data then:

[input[i, :] for i in 1:size(input, 1)]

If you do not want to make a copy of the data you can use views:

[view(input, i, :) for i in 1:size(input, 1)]

After some thought those are alternatives using broadcasting:

getindex.([input], 1:size(input, 1), :)
view.([input], 1:size(input, 1), :)
like image 191
Bogumił Kamiński Avatar answered Nov 27 '22 15:11

Bogumił Kamiński


I add one alternative too:

mapslices(x->[x], input,2)

Edit:

Warning! Now I see that mapslices return 3x1 matrix! (you could change it: mapslices(x->[x], input,2)[:,1])

I am unsatisfied. I don't like any solution we find yet. They are too complicated (think for example how to explain it to children!).

It is also difficult to find function like mapslices in doc too. BTW there is non-exported Base.vect function which could be used instead of anonymous x->[x].

I was thinking that sometimes is more clever to use bigger hammer. So I tried to find something with DataFrames

julia> using DataFrames
julia> DataFrame(transpose(input)).columns
3-element Array{Any,1}:
 [1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]
  1. unfortunately there is not DataFrame.rows
  2. result's type is Array{Any,1}
  3. I don't think it could be very quick

I hope Julia could get us better solution! :)

like image 25
Liso Avatar answered Nov 27 '22 15:11

Liso