How to convert a matrix to an array of arrays?

Q How to convert an array of an array to a matrix? we learned how to convert an array of arrays to a matrix. But what about the other way? How do we go from inputto outputas shown below?

input = [1 2 3; 4 5 6; 7 8 9]
output = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+4
source share
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 copy the data, you can use the views:

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

Some people think these are broadcast alternatives:

getindex.([input], 1:size(input, 1), :)
view.([input], 1:size(input, 1), :)
+7
source

I also add one alternative:

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

Edit:

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

. - , . (, , !).

, mapslices . BTW Base.vect, x->[x].

, . - 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
  • : Array { , 1}
  • ,

, !:)

+2

Source: https://habr.com/ru/post/1692173/


All Articles