How to use linspace understanding to create a matrix

I would like to create an nx 3 matrix, where n is the number of pixels (width * height).

x = linspace(-1, 1, width) y = linspace(-1, 1, height) r = 1.0 viewDirections = [[ij 1.0] for i in x for j in y] 

However, when I run this, I get:

 16-element Array{Array{Float64,2},1} 

not my desired 16x3 Array{Float64,2} . Obviously, I am not correctly using methods for constructing matrices. I tried using methods to create an array of tuples, but I cannot then convert these tuples to a matrix.

+5
source share
1 answer

The problem here is array comprehension will give us a nested array instead of Matrix . This is the correct understanding behavior, it will not make additional guesses for us, so we need to convert the nested array to the matrix manually, which can be done using vcat with the splating ( ... ) operator:

 julia> vcat(viewDirections...) 6ร—3 Array{Float64,2}: -1.0 -1.0 1.0 -1.0 1.0 1.0 0.0 -1.0 1.0 0.0 1.0 1.0 1.0 -1.0 1.0 1.0 1.0 1.0 

It seems you are building homogeneous coordinates from a 2D Euclidean space. Using Base.Iterators.product is a more concise and reliable way to create an iterator:

 julia> w = linspace(-1,1,3) -1.0:1.0:1.0 julia> h = linspace(-1,1,2) -1.0:2.0:1.0 julia> r = 1.0 1.0 julia> viewDirections = [collect(i) for i in Iterators.product(w, h, r)] 3ร—2 Array{Array{Float64,1},2}: [-1.0, -1.0, 1.0] [-1.0, 1.0, 1.0] [0.0, -1.0, 1.0] [0.0, 1.0, 1.0] [1.0, -1.0, 1.0] [1.0, 1.0, 1.0] julia> hcat(viewDirections...).' 6ร—3 Array{Float64,2}: -1.0 -1.0 1.0 0.0 -1.0 1.0 1.0 -1.0 1.0 -1.0 1.0 1.0 0.0 1.0 1.0 1.0 1.0 1.0 

Note that the coordinate order is different from your original version, which, since Julia is the main column, Iterators.product will iterate over the most correct dimension โ€œoutestlyโ€, i.e. [[ijr] for j in y for i in x ] . If ordering is important in your use case, just pay attention to it. Here are some test results when the width/height gets large:

 julia> w = linspace(-1,1,300) -1.0:0.006688963210702341:1.0 julia> h = linspace(-1,1,200) -1.0:0.010050251256281407:1.0 julia> foo(w,h,r) = hcat([collect(i) for i in Iterators.product(w, h, r)]...).' julia> bar(w,h,r) = vcat([[ijr] for i in w for j in h]...) julia> @btime foo($w,$h,$r); 6.172 ms (60018 allocations: 10.99 MiB) julia> @btime bar($w,$h,$r); 11.294 ms (360028 allocations: 17.02 MiB) 
+2
source

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


All Articles