Assigning different color to NaN values in 2D matrix

20 views (last 30 days)
I have a 2D matrix (600x500) which has different values ranging from 0 to 30 and some NaN values. I need to show it as a color image with each pixel having a code code corresponding to its value. I am doing this with imagesc/pcolor.
However, I need to show the NaN values in a completely different color, say white or black to differentiate them from rest of the elements in the matrix. How do I do this?
At present, the NaN values are getting interpreted as zeros and are being shown as the same color as zero.
  3 Comments
Matt Kindig
Matt Kindig on 25 Apr 2013
I think your -1 trick is the right way to go. To force those values to be white (or black), you can define a custom colormap for your imagesc/pcolor call. For example:
mycolormap = [ ones(1,3); jet(30)]; %tack on a white row to your colormap
imagesc(...) %or pcolor(...)
colormap(mycolormap); %call your custom colormap
Cedric
Cedric on 25 Apr 2013
Edited: Cedric on 25 Apr 2013
You could also overlay whatever you want to indicate these locations, e.g.
imagesc(data) ;
[r,c] = find(isnan(data)) ;
hold on ;
plot(c, r, 'ro') ;

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 25 Apr 2013
Try this demo, make sure you read the comments. I make an array, then set random pixels to NaN. Then I set the nan pixels to red. By the way, don't use pcolor().
clc; % Clear command window.
close all; % Close all figure windows except those created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 15;
image(imageArray);
% Apply a colormap
cmap = jet(256);
colormap(cmap);
colorbar
title('No NaNs', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Now set random elements to NAN
uiwait(msgbox('Now set random elements to NAN'));
randomLocations = randperm(numel(imageArray), 2000);
imageArray(randomLocations) = nan;
image(imageArray);
colorbar
title('With 2000 NaNs', 'FontSize', fontSize);
% Now find the nans and set them to some gray level
% preferably one that isn't used at all,
% but let's set them to zero.
uiwait(msgbox('Now find the nans and set them to 0'));
imageArray(isnan(imageArray)) = 0;
image(imageArray);
colorbar
title('With NaNs set to zero', 'FontSize', fontSize);
uiwait(msgbox('Now find the 0s and set them to red'));
% Now let's change the color map for gray level 0
cmap(1, :) = [1 0 0]; % Set to red.
colormap(cmap); % Apply new colormap.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!