View License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from

Be the first to rate this file! 3 Downloads (last 30 days) File Size: 2.86 KB File ID: #41966 Version: 1.0
image thumbnail



Benjamin Kraus (view profile)


Convert a 2D matrix into an image with NaNs replaced by white

| Watch this File

File Information

nantowhite - Convert a 2D matrix into an image with NaNs replaced by white

  [im, clim] = nantowhite(cvals)
  [im, clim] = nantowhite(cvals, clim)
  [im, clim] = nantowhite(cvals, clim, cmap)

nantowhite takes in an N x M matrix of values ('cvals') and outputs an N x M x 3 uint8 image that can be displayed on screen using 'image'. This function replaces 'imagesc' for situations where there are NaN values in the input matrix. Instead of displaying 'NaN' values using the first value in the colormap, it displays them using white. You can replace what would originally be 'imagesc(cvals)' with 'image(nantowhite(cvals))'.

This function was created because alpha layers used to make 'NaN' values transparent were ignored when images were saved in a vector format.

See the demo code below to get 'colorbar' to show the correct limits when using this function.

cvals - A 2D matrix to be converted to an image. Any NaN values in the
        matrix will be converted into white pixels in the output image.

clim - The minimum and maximum value on the colorscale used for
       converting values in 'cvals' into colors in the output image.
       An empty maxtix is ignored. Positive or negative 'inf' values
       are replaced by the minimum or maximum value in 'cvals'.

cmap - The color map to use for conversion from 'cvals' into colors.

im - An N x M x 3 uint8 image matrix. [N,M] = size(cvals)

clim - The color limits used when converting values to color pixels.


[X,Y] = meshgrid(-2*pi:pi/16:2*pi);
cvals = 20*cos(X).*sin(Y);
cvals(1:20,1:20) = NaN;
cvals(randperm(numel(cvals),400)) = NaN;

Original Code:
  figure; ax = axes();

Modified Code:
  figure; ax = axes();
  [im, cl] = nantowhite(cvals);

Required Products MATLAB
MATLAB release MATLAB 7.13 (R2011b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.

Contact us