hello everyone I am new to Julia. Earlier I was using Matlab but now I have started to work in Julia. I would like to know is there any similar function available in julia like Meshgrid which is available in matlab. Please help.
Yup, see VectorizedRoutines.jl
Also worth saying: as you use Julia more and more, you’ll probably use meshgrid
less and less. Here’s a nice explanation of why (for an outdated Julia version, but other than suggesting you ignore the comments about performance—all those issues were fixed long ago—the syntax seems pretty applicable now): https://groups.google.com/g/julia-users/c/83Pfg9HGhGQ/m/9G_0wi-GBQAJ
A few months ago, while teaching conformal mapping, I rolled my own
"""
duplicate of matlab meshgrid function
"""
function meshgrid(xin,yin)
nx=length(xin)
ny=length(yin)
xout=zeros(ny,nx)
yout=zeros(ny,nx)
for jx=1:nx
for ix=1:ny
xout[ix,jx]=xin[jx]
yout[ix,jx]=yin[ix]
end
end
return (x=xout, y=yout)
end
Modern Julia is better:
x = 1:3
y = 1:5
x' .* ones(5)
#=
5Ă—3 Array{Float64,2}:
1.0 2.0 3.0
1.0 2.0 3.0
1.0 2.0 3.0
1.0 2.0 3.0
1.0 2.0 3.0
=#
ones(3)' .* y
#=
5Ă—3 Array{Float64,2}:
1.0 1.0 1.0
2.0 2.0 2.0
3.0 3.0 3.0
4.0 4.0 4.0
5.0 5.0 5.0
=#
neat! when was that?
also, can you do 3D arrays with the same bcast trick?
The only reason to make a meshgrid in Julia now is that you can do it as a lazy object without an array backing, so it could be like a 2D or 3D Range
, meaning a 10,000,000 x 10,000,000 grid is representable in like 500 bytes.
You don’t need meshgrid in Julia. In fact, it is rarely needed even in Matlab these days, after they introduced a type of broadcasting.
I would recommend to not use meshgrid, and instead learn idiomatic Julia.
Same thing with repmat
. Never needed in Julia, virtually never needed in Matlab. It’s old-style Matlab.
old-style Matlab.
This was the moment I realized I am now old.
I meant “classic Matlab”
Can you help with how to plot a structured grid using these points in Julia?
I am also confused. I use this for contour
in PyPlot, where the help files tell me to use meshgrid. How can I avoid meshgrid without finding a different plotting package?
You don’t need a meshgrid for contour plotting with PyPlot — you can pass 1d arrays for the axes and it knows how to broadcast them, and you write 2d functions of the axes variables by broadcast operations as well:
using PyPlot
x = range(0,2,length=100)' # note ': this is a row vector
y = range(0,4,length=200)
z = @. sin(x) * cos(y) # broadcasts to 2d array
contour(x, y, z)
Thanks. I’m even older than @jlchan and transcribed my stuff from (no joke) 20 year old matlab.
This is the corresponding Matlab code, btw:
x = linspace(0, 2, 100);
y = linspace(0, 4, 200).';
z = sin(x) .* cos(y); % broadcasts to 2d array
contour(x, y, z)
I have seen the error in my ways and will go forth and sin in a different way in the future.
Remember to cos as well!
I will do that as I sit in the sun and work on my tan.
Instead of sin
ning, sec
and ye shall find!