n = 6;
A = (rand(n,n,n) > 0.5);

# the following function can be in a standalone file too. the bug still happens.
function voxel2 (pos, sz = [1 1 1], color = [0.8 0.8 0.8], alpha = 0.2)
  verts = (dec2bin(0:7)=='1') .* sz + pos;
  faces = [1 2 4 3; 5 6 8 7; 1 3 7 5; 2 4 8 6; 1 2 7 5; 3 4 8 7]; # the 6 faces of the cube in cyclic order
  patch ("Faces",faces, "Vertices",verts, "facecolor",color, "facealpha",alpha);
endfunction

for i = 1:10
  # the bug does not happen if this loop executes 7 times or fewer. 8 times or more it is repeatable.
  # in production code, matrix A changes for each iteration but for showing this bug it's been frozen
  figure(i); hold on; axis equal; axis off; view(135, atan(1/sqrt(2))*180/pi);
  for p = 1:n
    for q = 1:n
      for r = 1:n
        if (A(p,q,r))
          voxel2 ([p q r]);
        endif
      endfor
    endfor
  endfor
  # saveas (gcf, sprintf ("test%02d.png", i)); # this has been commented out for speeding up bug test execution
endfor
