When you save the figure using the saveas function, MATLAB uses a default resolution of 150 DPI (dots per inch) to create the PNG image. The default renderer used by MATLAB to create PNG images is the OpenGL renderer, which does not always produce consistent results when dealing with transparency and alpha maps. This is likely the cause of the issue you are experiencing, where the NaN pixels in the image are shown as white instead of black.
To fix this issue, you can try using a different renderer when saving the figure as a PNG. One option is to use the -r option with the print function to set a higher resolution and a different renderer. For example, you can try setting the renderer to 'Painters' and the resolution to 300 DPI using the following code:
print(gcf, 'testimage.png', '-dpng', '-r300', '-painters');
This code saves the figure with a resolution of 300 DPI and uses the 'Painters' renderer instead of the default OpenGL renderer. The 'Painters' renderer is a vector-based renderer that is better suited for creating high-quality images with transparency and alpha maps.
Alternatively, you can try using the exportgraphics function introduced in MATLAB R2020a to save the figure as a PNG with transparency. This function allows you to specify the format and resolution of the output image, as well as any additional options such as setting the background color. Here is an example of how to use the exportgraphics function to save the figure as a PNG with transparency:
exportgraphics(gcf, 'testimage.png', 'Resolution', 300, 'BackgroundColor', 'k', 'ContentType', 'image/png');
This code saves the figure with a resolution of 300 DPI, sets the background color to black, and specifies the output format as PNG. The resulting PNG image should preserve the black background color and the NaN pixels in the image should be shown as transparent.