Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract rows / columns of a matrix into separate variables

Tags:

julia

The following question came up in my course yesterday:

Suppose I have a matrix M = rand(3, 10) that comes out of a calculation, e.g. an ODE solver.

In Python, you can do

x, y, z = M

to extract the rows of M into the three variables, e.g. for plotting with matplotlib.

In Julia we could do

M = M'  # transpose 
x = M[:, 1]
y = M[:, 2]
z = M[:, 3]

Is there a nicer way to do this extraction? It would be nice to be able to write at least (approaching Python)

x, y, z = columns(M)

or

x, y, z = rows(M)

One way would be

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

but this will make an expensive copy of all the data.

To avoid this would we need a new iterator type, ColumnIterator, that returns slices? Would this be useful for anything other than using this nice syntax?

like image 980
David P. Sanders Avatar asked Oct 07 '15 06:10

David P. Sanders


1 Answers

columns(M) = [ slice(M,:,i) for i in 1:size(M, 2) ]

and

columns(M) = [ sub(M,:,i) for i in 1:size(M, 2) ]

They both return a view, but slice drops all dimensions indexed with scalars.

like image 183
Reza Afzalan Avatar answered Oct 27 '22 13:10

Reza Afzalan