catastrophic-failure
catastrophic-failure

Reputation: 3905

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]]

Upvotes: 8

Views: 1651

Answers (2)

Liso
Liso

Reputation: 2260

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! :)

Upvotes: 2

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

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), :)

Upvotes: 13

Related Questions