logo

Broadcasting of Multivariable Functions in Julia 📂Julia

Broadcasting of Multivariable Functions in Julia

Overview

Introducing how to broadcast multivariable functions in Julia. Like in Python, you can create a meshgrid, or you can easily calculate by creating vectors for each dimension.

Bivariate Functions

$$ u(t,x) = \sin(\pi x) e^{-\pi^{2}t} $$

To plot the function $(t,x) \in [0, 0.35] \times [-1,1]$ as above, the function values can be calculated like this:

x = LinRange(-1., 1, 100)
t = LinRange(0., 0.35, 200)'

u1 = @. sin(π*x)*exp(- π^2 * t)
heatmap(t', x, u1, xlabel="t", ylabel="x", title="Fig. 1")

fig1.png

After defining the function itself, the same results can be obtained by creating a 2D grid as follows:

U(t,x) = sin(π*x)*exp(- π^2 * t)
x = LinRange(-1., 1, 100)
t = LinRange(0., 0.35, 200)'

X = x * fill!(similar(t), 1)
T = fill!(similar(x), 1) * t

u2 = U.(T,X)
heatmap(t', x, u2, xlabel="t", ylabel="x", title="Fig. 2")

fig2.png

Trivariate Functions

$$ u(x,y,t) = e^{-x^{2} - 2y^{2}}e^{-\pi^{2}t} $$

If you want to get the function values of $u$ over the space-time domain $(x,y,t) \in [-1,1] \times [-1,1] \times [0, 0.35]$, you can just create vectors that have dimensions only for each variable and broadcast.

If you want to create a 3D mesh and broadcast, see here.

julia> x = reshape(LinRange(-1., 1, 100), (100,1,1))
    100×1×1 reshape(::LinRange{Float64, Int64}, 100, 1, 1) with eltype Float64:
julia> y = reshape(LinRange(-1., 1, 100), (1,100,1))
    1×100×1 reshape(::LinRange{Float64, Int64}, 1, 100, 1) with eltype Float64:
julia> t = reshape(LinRange(0.,0.35, 200), (1,1,200))
    1×1×200 reshape(::LinRange{Float64, Int64}, 1, 1, 200) with eltype Float64:

julia> u3 = @. exp(-x^2) * exp(-2y^2) * exp(- π^2 * t)
    100×100×200 Array{Float64, 3}:

anim = @animate for i ∈ 1:200
    surface(u3[:,:,i], zlims=(0,1), clim=(-1,1))
end

anim1.gif

Code Details

using Plots
cd = @__DIR__

# Fig. 1
x = LinRange(-1., 1, 100)
t = LinRange(0., 0.35, 200)'

u1 = @. sin(π*x)*exp(- π^2 * t)
heatmap(t', x, u1, xlabel="t", ylabel="x", title="Fig. 1")
savefig(cd*"/fig1.png")

# Fig. 2
U(t,x) = sin(π*x)*exp(- π^2 * t)
x = LinRange(-1., 1, 100)
t = LinRange(0., 0.35, 200)'

X = x * fill!(similar(t), 1)
T = fill!(similar(x), 1) * t

u2 = U.(T,X)
heatmap(t', x, u2, xlabel="t", ylabel="x", title="Fig. 2")
savefig(cd*"/fig2.png")

# gif 1
x = reshape(LinRange(-1., 1, 100), (100,1,1))
y = reshape(LinRange(-1., 1, 100), (1,100,1))
t = reshape(LinRange(0.,0.35, 200), (1,1,200))

u3 = @. exp(-x^2) * exp(-2y^2) * exp(- π^2 * t)
anim = @animate for i ∈ 1:200
    surface(u3[:,:,i], zlims=(0,1), clim=(-1,1), title="Anim. 1")
end
gif(anim, cd*"/anim1.gif", fps=30)

Environment

  • OS: Windows11
  • Version: Julia v1.8.3, Plots v1.38.6