Extract rows / columns of a matrix into separate variables

The following question appeared in my course yesterday:

Suppose I have a matrix M = rand(3, 10) , which leaves the calculation, for example. ODE solver.

In Python you can do

x, y, z = M

to extract strings from M into three variables, for example. to build with matplotlib .

In Julia we could do

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

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

 x, y, z = columns(M) 

or

 x, y, z = rows(M) 

One of the methods -

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

but it will make an expensive instance of all the data.

To avoid this, we need a new type of iterator, ColumnIterator , which returns slices? Would it be useful for anything other than using this pretty syntax?

+5
source share
2 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) ]

Both of them return a view, but a slice reduces all sizes indexed using a scalar.

+1
source

A good alternative I just found if M is Vector of Vector (instead of matrix) uses zip :

 julia> M = Vector{Int}[[1,2,3],[4,5,6]] 2-element Array{Array{Int64,1},1}: [1,2,3] [4,5,6] julia> a, b, c = zip(M...) Base.Zip2{Array{Int64,1},Array{Int64,1}}([1,2,3],[4,5,6]) julia> a, b, c ((1,4),(2,5),(3,6)) 
+1
source

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


All Articles