RangerBob
RangerBob

Reputation: 493

How to convert a Matrix into a Vector of Vectors?

I have the following matrix A = [1.00 2.00; 3.00 4.00] and I need to convert it into a vector of Vectors as follows:

A1 = [1.00; 3.00] A2 = [2.00; 4.00]

Any ideas?

Upvotes: 7

Views: 7622

Answers (4)

Abhinav Bhatia
Abhinav Bhatia

Reputation: 41

It's even simpler.

eachcol is all you need. It's an abstract vector.

A=eachcol(A)

Now A[1] is [1.00; 3.00], and A[2] is [2.00; 4.00].

With this approach, there are no memory allocations. Everything is based on views.

Upvotes: 4

erouviere
erouviere

Reputation: 21

Another option is B = [eachcol(A)...]. This returns an variable with type Vector{SubArray} which might be fine depending on what you want to do. To get a Vector{Vector{Float64}} try,

B = Vector{eltype(A)}[eachcol(A)...]

Upvotes: 2

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22215

tl;dr
This can be very elegantly created with a list comprehension:

A = [A[:,i] for i in 1:size(A,2)]


Explanation:

This essentially converts A from something that would be indexed as A[1,2] to something that would be indexed as A[2][1], which is what you asked.

Here I'm assigning directly back to A, which seems to me what you had in mind. But, only do this if the code is unambiguous! It's generally not a good idea to have same-named variables that represent different things at different points in the code.

NOTE: if this reversal of row / column order in the indexing isn't the order you had in mind, and you'd prefer A[1,2] to be indexed as A[1][2], then perform your list comprehension 'per row' instead, i.e.

A = [A[i,:] for i in 1:size(A,1)]

Upvotes: 14

Alexander Morley
Alexander Morley

Reputation: 4181

It would be much better simply to use slices of your matrix i.e. instead of A1 use A[:,1] and instead of A2 use A[:,2]

If you really need them to be "seperate" objections you could try creating a cell array like so:

myfirstcell = cell(size(A,2)) for i in 1:size(A,2) myfirstcell[i] = A[:,i] end

See http://docs.julialang.org/en/release-0.4/stdlib/arrays/#Base.cell

(Cell arrays allow several different types of object to be stored in the same array)

Upvotes: 1

Related Questions