Work around for Meshgrid of python into julia

I am trying to plot a potential diagram for two charge plates. I have a code which does that in python. I am now trying to convert that code block into julia. But I am unable to do so. Can someone help?
The code in python :


The code I have written in julia :

N = 100
grids = zeros(N,N,N) .+ 0.5
grids[30:70,30:70, 20] .= 1
grids[30:70,30:70, 80] .= 0
mask_pos = grids .== 1
mask_nev = grids .== 0
heatmap(mask_pos[:,:,20])
xv = yv = zv = collect(1:N)
grids = 1 .- (zv /100)
contour(grids[0,:,:])

But this is showing a error :

BoundsError: attempt to access 100-element Vector{Float64} at index [0, 1:1, 1:1]
Stacktrace:
 [1] throw_boundserror(A::Vector{Float64}, I::Tuple{Int64, Base.Slice{Base.OneTo{Int64}}, Base.Slice{Base.OneTo{Int64}}})
   @ Base ./abstractarray.jl:703
 [2] checkbounds
   @ ./abstractarray.jl:668 [inlined]
 [3] _getindex
   @ ./multidimensional.jl:874 [inlined]
 [4] getindex(::Vector{Float64}, ::Int64, ::Function, ::Function)
   @ Base ./abstractarray.jl:1241
 [5] top-level scope
   @ ~/Desktop/Articles_Code/Codes/Julia/projects/Electric_field.jl:15

Can someone help?

The error message tells you how the error occurs:

You have created a grid, grids, but here you replace that grid with grids = 1 .- (zv /100), so the 3D grid is now gone. The actual error then is triggered on the next line, since Julia Arrays have one-based indexing, but you are giving it 0, which is a BoundsError.

I’m not sure exactly what you would like to do, but if you are looking to plot a slice of the original grid, maybe first remove the redefinition of grids, and then try

contour(grids[1,:,:]) 
2 Likes

BTW, there are two issues with this line. Firstly, it allocates a Vector, probably needlessly. You can in most cases just use 1:N instead of collect(1:N). It’s faster and better. Secondly, you are making xv, yv, and zv all point to the exact same vector, which means that if you modify one of them, all three are affected.

My general advice is ‘never use collect’. Only use it if your code cannot work without it.

1 Like

Seriously… I am a fool… Yes… That 0 and i never noticed :expressionless::disappointed_relieved:

One more thing. I’m not exactly sure why you are moving code from numpy to Julia, but if it is for performance reasons, you should be aware that writing Julia in ‘numpy-style’ is not likely to speed it up. In fact, the Julia version will probably be slower, since Julia slices create copies.

If you want fast code, you should read the performance tips in the manual.

2 Likes

But still it’s not giving me same plot…

What is your updated code? Please include the library imports as well. Which plot library are you using?