function [idx] = grid2idx3D(x, y, z, nelx, nely, nelz)
%grid2idx converts element numbers x and y into topopt indices idx
%   First check that the supplied elements are within the bounds, then
%   convert the element locations to topopt indices
%% Check bounds

assert( all(floor(x) == x), "Check that supplied elements are integer");
assert( all(floor(y) == y), "Check that supplied elements are integer");
assert( all(floor(z) == z), "Check that supplied elements are integer");
assert( all(x<=nelx) , "Check that supplied elements are within bounds!");
assert( all(x>=1)  , "Check that supplied elements are within bounds!");
assert( all(y<=nely)  , "Check that supplied elements are within bounds!");
assert( all(y>=1)  , "Check that supplied elements are within bounds!");
assert( all(z<=nelz)  , "Check that supplied elements are within bounds!");
assert( all(z>=1)  , "Check that supplied elements are within bounds!");
%% Convert to TopOpt indices
% idx = nely * x - y + 1; %2d
idx = x + (y-1) * nelx + (z-1) * (nelx * nely);
end

