Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Matrix into a Vector of Vectors?

Tags:

julia

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?

like image 754
RangerBob Avatar asked Dec 14 '22 04:12

RangerBob


1 Answers

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)]
like image 54
Tasos Papastylianou Avatar answered Dec 21 '22 03:12

Tasos Papastylianou