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]]
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.
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.
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 ...
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), :)
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]
DataFrame.rows
I hope Julia could get us better solution! :)
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