How to efficiently create a table/array through known function?

As the question, if I want to create a table by a function, I may use collect:

@elapsed collect(Vector{Float64}(m*[2*pi,(2pi)/sqrt(3)]+n*[0,(4*pi)/sqrt(3)]) for m in range(0.,1.,1001), n in range(0.,1.,1001))

with output 0.9724441 in my laptop.
However, I could directly use Table in Mathematica:

    N[m*{2 \[Pi], (2 \[Pi])/Sqrt[3]} + n*{0, (4 \[Pi])/Sqrt[3]}]], 
    Sequence @@ 
     N[{{m, 0, 1, 1/1001}, {n, 0, 1, 1/1001}}]]]] // AbsoluteTiming

with only 0.08 seconds. Therefore, could I try some more efficient method to generate an list?

What you are creating here is a matrix of vectors. Is that what you want?

If it is that, and the vectors of the matrix have actually only 2 elements, you can create them with StaticArrays, by replacing the [] constructors by SVector():

julia> using StaticArrays

julia> @elapsed collect((m*SVector(2*pi,(2pi)/sqrt(3))+n*SVector(0,(4*pi)/sqrt(3))) for m in range(0.,1.,1001), n in range(0.,1.,1001))

Nevertheless, I find likely that that is not exactly what you want for an output (I cannot test what the Mathematica code produces).


Because each matrix entry is a two-element Vector, you’ll have one newly allocated vector times the number of elements in your matrix, the multiplications and addition you’re doing even increases the allocations. Instead you can work with tuples, for example:

function func()
    [m .* (2*pi,(2pi)/sqrt(3)) .+ n .* (0.0,(4*pi)/sqrt(3)) for m in range(0.,1.,1001), n in range(0.,1.,1001)]

@time func()
0.005967 seconds (2 allocations: 15.289 MiB)

Edit: A tad slower than @lmiq :slight_smile:


Thanks for your reply. SVector is an extremely effective function, which can solve my problem.

Thanks for your effectual suggestion. Could I know what is the mechanism of [space].* ? It seems I couldn’t directly multiply a number with an tuple?

It’s broadcasting, or syntactic loop fusion:

1 Like

That is why I suggested the SVector. These static vectors are just tuples as well, but for which all arithmetic is defined. If that is important or not it depends on what you are doing with the vectors afterwards.