Hello there,
I was wondering how could we bulid a list like this:
I have a array x = [1,2,3,4] and y = [5,6,7,8] and now I would like to come up a new array like
z = [ [1,5], [2,6], [3,7], [4,8] ] to reflects that these are coordinates. In my case I have 500 elements in x and y so it is impossible to do like above. And I tried several naive methods but all failed.
Could anyone give some suggesstions to generate this kind of z list by more general method?
Thank you very much!
julia> x = [1,2,3,4]; y = [5,6,7,8];
julia> z = [ [x[i],y[i]] for i in 1:length(x) ]
4-element Vector{Vector{Int64}}:
[1, 5]
[2, 6]
[3, 7]
[4, 8]
Alternatively
julia> z = [[a, b] for (a, b) ∈ zip(x, y)]
4-element Vector{Vector{Int64}}:
[1, 5]
[2, 6]
[3, 7]
[4, 8]
Ah! Indeed! Thank you for this kind, quick and helpful response!
Thank you a lot ! !
One more option:
xy = collect(eachrow([x y]))
Got it ! Thank you!
For coordinate vectors, I would strongly consider using StaticArrays.jl for performance reasons.
Then you would just use SVector.(x,y)
You can use tuple.(x, y)
if you do not want external dependency and ok to work with tuples.
Why not just
zip(x, y)
?
Do you really need to turn them into vectors?
If you provide a bit more background on what you want to do, it would be possible to tell. Often you don’t need a vector (or vector of vectors), just something to iterate over and do what you actually want to accomplish on each pair of coordinates.
Thank you kindly all !
Yes, I would like to simulate a 2D motion of some particles in a known domain and thay moves randomly. I have their initial positions and in the domain there are some holes which would absorb particles entered in. So I think I might need to store their coordinates in each time step and aslo need to determine whether to enter the holes.
Ok, I can’t say that this is unnecessary, but think it over. If you can process the coordinate pairs, one after the other, you won’t need an intermediate array.
Sorry, can’t help but share my favorite way for doing this: collect.(zip(x,y))
. Then you can also try taking away the collect.
at some point and see if you actually needed to collect.
Or: collect.(tuple.(x,y))
Then definitely you want StaticArrays. If it helps, this package is an educational package that does those kind of simulations of particles using that kind of structure. The codes are intended to be very simple and readable. The tutorial is in Spanish, but browser automatic translation tools are pretty good (the codes are in English).
Got it! Going to check it out. Thank you again for your great help!
or just tuple.(x, y)
@Skoffer has already the copyright (see further up…)
Oops I missed that, there, a well-deserved heart for @Skoffer