The correct way to (un) zip arrays in Julia

I used the PyPlot library in Julia to plot, and the scatter function seems to be a "bit" inconvenience, namely, that takes only coordinates as two arguments: one array for all x values, and the other for all y values, i.e.

scatter(xxs,yys) 

with x=[x1,x2,...] and y=[y1,y2,...] .

If I have a set or tuple with coordinate points, for example,

 A=([x1,y1],[x2,y2],...) 

using pyplot / matplotlib directly in Python, solves the inconvenience in a single liner, like atested https : //stackoverflow.com/a/3/7/12/16/16/16/16/16/16/16/...

 plt.scatter(*zip(*li)) 

but it seems that the zip on Julia works in a completely different way. So far I have come up with the following solution, but it seems rather inelegant:

 x=[] y=[] for j in selectos append!(x,j[2]) append!(y,j[1]) end scatter(x,y, marker="o",c="black") 

Is there a more “functional” or single-line (or two liners) approach?

+5
source share
2 answers

As mentioned in another answer, Julia can use the same approach, i.e. scatter(zip(A...)...) , but it is very slow for large vectors and should be avoided.

Another possibility is to use getindex.(A, i) to get the vector of all the ith elements of the vectors in A

 julia> A = [[i, 10i] for i=1:5] 5-element Array{Array{Int64,1},1}: [1, 10] [2, 20] [3, 30] [4, 40] [5, 50] julia> getindex.(A,1) 5-element Array{Int64,1}: 1 2 3 4 5 julia> getindex.(A,2) 5-element Array{Int64,1}: 10 20 30 40 50 
+3
source

I can think of three approaches:

 using PyPlot A = ([1,2],[3,4],[5,6],[7,8]) # approach 1 scatter(zip(A...)...) # approach 2 B = hcat(A...) @views scatter(B[1,:], B[2,:]) # approach 3 scatter([x[1] for x in A], [x[2] for x in A]) 

The first is probably the most functional.

In the second, you get B , which is easier to work with if you need to analyze the data; notabene @views requires Julia 0.6, but it can be omitted.

The third is probably the easiest way to understand.

+2
source

All Articles