logo

How to Create a Meshgrid in Julia 📂Julia

How to Create a Meshgrid in Julia

Overview

There is no direct equivalent to the meshgrid() function used in Python and MATLAB. If you only want to obtain the function values on a grid, there is a simpler method that does not require creating a grid.

Code

2D

Multiplying a column vector by a row vector gives the same result as taking the Kronecker product of a column vector and a row vector.

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

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

u1 = U.(T,X)
heatmap(t', x, u1, title="Fig 1")

fig1.png

When using the Kronecker product,

using LinearAlgebra

X = kron(x, ones(size(t)))
T = kron(ones(size(x)), t)

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

julia> u1 == u2
true

fig2.png

3D1

U(x,y,t) = exp(-x^2) * exp(-2y^2) * exp(- π^2 * t)

x = LinRange(-1., 1, 100)
y = LinRange(-1., 1, 100)
t = LinRange(0.,0.35, 50)

X = getindex.(Iterators.product(x, y, t), 1)
Y = getindex.(Iterators.product(x, y, t), 2)
T = getindex.(Iterators.product(x, y, t), 3)

u3 = U.(X,Y,T)

anim = @animate for i ∈ 1:50
    surface(u3[:,:,i], zlims=(0,1), clim=(-1,1), title="Anim. 1")
end

anim1.gif

Full Code

using Plots
cd = @__DIR__

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

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

u1 = U.(T,X)
heatmap(t', x, u1, title="Fig 1")
savefig(cd*"/fig1.png")

# kron
using LinearAlgebra

X = kron(x, ones(size(t)))
T = kron(ones(size(x)), t)

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

u1 == u2

# 3d
U(x,y,t) = (1/4) * exp(-x^2) * exp(-2y^2) * exp(- π^2 * t)

x = LinRange(-2., 2, 100)
y = LinRange(-2., 2, 100)
t = LinRange(0.,0.35, 50)

X = getindex.(Iterators.product(x, y, t), 1)
Y = getindex.(Iterators.product(x, y, t), 2)
T = getindex.(Iterators.product(x, y, t), 3)

u3 = U.(X,Y,T)

anim = @animate for i ∈ 1:50
    surface(u3[:,:,i], zlims=(0,0.5), clim=(0,0.3), title="Anim. 1")
end
gif(anim, cd*"/anim1.gif", fps=10)

Environment

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