Improve performance of this index creation and accessing code

How to improve the performance of clp(j) function given below. Please suggest faster version of this code.
I am converting spherical coordinates to Cartesian and placing color values to exact location in data. Otherwise i get cuboid on plotting but i should get distorted shape.

nx=23; ny=5; nz=17;
X=rand(nx*ny*nz); Y=rand(nx*ny*nz); Z=rand(nx*ny*nz); C=rand(nx*ny*nz);
xmin = -0.00010490733f0
ymin = -176.07669f0
zmin = -1200.0f0
sx = 0.97817904f0
sy = 0.27828765f0
sz = 0.24079268f0
field = fill(NaN32, nx,ny,nz);

function clp(j)
	xi = Int32(round((X[j] - xmin) * sx)) + 1   #slow line
	yi = Int32(round((Y[j] - ymin) * sy)) + 1   #slow line
	zi = Int32(round((Z[j] - zmin) * sz)) + 1   #slow line
	ix = max(1, min(nx, xi))
	iy = max(1, min(ny, yi))
	iz = max(1, min(nz, zi))
	field[ix, iy, iz] = C[j]
end

for j in eachindex(X)
	clp(j)
end

another alternative form of clp(j) is :backhand_index_pointing_down:

for (xi, yi, zi, ci) in zip(X, Y, Z, C)
    ix = clamp(Int(round((xi-xmin)*sx)) + 1, 1, nx)
    iy = clamp(Int(round((yi-ymin)*sy)) + 1, 1, ny)
    iz = clamp(Int(round((zi-zmin)*sz)) + 1, 1, nz)
    field[ix, iy, iz] = ci
end

Accessing a lot of untyped globals would stop most compiler optimizations.

1 Like