The best way to define two or more arrays, similar to a given one

Working example with no similars:

using Plots
pyplot()

ru, rv = -1.5:0.1:1.5, -1:0.1:1
u, v = [ui for ui in ru, vi in rv], [vi for ui in ru, vi in rv]

x = @. u*u - v 
y = @. 2*u+u*v
z = @. v+u-u^2

surface(x, y, z; colorbar=false, size=(500, 400))

image

Please pay attention to the positions of @.s.

Postscript: (for further clarity)

For an AbstractVector u, the code @. x = f(u) is essentially equivalent to

for i in eachindex(u)
    x[i] = f(u[i])
end

If x is not defined in this code, then we get “UndefVarError: x not defined”.

But the code x = @. f(u) is essentially equivalent to

x = [f(u[i]) for i in eachindex(u)]

We obtain the new vector x.

If we just notice this difference, we can remove the redundant similars.

Working example:

u = range(0, 1; length=7)
@. x = sinpi(u)
UndefVarError: x not defined
...
x = @. sinpi(u)
7-element Vector{Float64}:
 0.0
 0.5
 0.8660254037844386
 1.0
 0.8660254037844387
 0.4999999999999999
 0.0
2 Likes