MATLAB: Why do the colors render strangely in MATLAB 7.8 (R2009a) when I place three patch objects at location Z=0 and rotate the axes coordinates using z-buffer or opengl rendering

floatingMATLABobjectspatchpointprecisionrendering

I use the following code to create three patch objects using Z-buffer rendering.
p1 = patch([-1 1 1 -1],[-1 -1 1 1],[0 0 0 0])
p2 = patch([-.75 .75 .75 -.75],[-.75 -.75 .75 .75],[0 0 0 0],'red')
p3 = patch([-.7 .7 .7 -.7],[-.7 -.7 .7 .7],[0 0 0 0],'blue')
set(gcf,'Renderer','ZBuffer')
When I use the rotate tool to rotate the plot, I expect the smallest patch (blue) to stay on top. However, the colors of the patches flicker. It does not look like the smallest patch always stays on top.

Best Answer

When the figure is viewed at a different angle, the position of each patch along a vector normal to the screen must be recalculated for every pixel using the location of the patch vertices. This calculation is limited to floating point precision, i.e. only the numbers that are representable using IEEE 754 floating point standard. If for all patches, the position of the pixel should theoretically be the square root of 2, one patch may approximate this as the floating point value above square root of two and another patch may approximate this as the floating point value below square root of 2. The patch that has the largest value (i.e. farther along the vector normal to the screen) is the one whose color gets represented.
One workaround is to use the 'Painters' renderer. Alternatively, you could offset the patches in Z or ensure that the patches do not overlap with each other.