Recolor imagesc Inf values in Matlab

3 views (last 30 days)
Martin Grunnill
Martin Grunnill on 13 May 2015
Commented: Martin Grunnill on 14 May 2015
I am using imagesc to display data from matrices. The matrices contain NaNs and Inf values. I am able to recolour NaNs to the background colour. I am using the jet colour map and I would like to recolour Inf values to black or another colour that is not the background colour or on the jet colour scheme. Matlab by default colours Inf values as same as the maximum value. What follows is a brief example code, to give an idea of what I mean.
a = [1 2 NaN; 4 Inf 6; 7 5 3];
%// Matrix of data
test_image= imagesc(a);
%// Creates imagesc figure.
colormap('jet');
%// Uses jet color scheme.
set(test_image,'alphadata',~isnan(a))
%// Ignores NaN values and sets NaN values to background colour.
colorbar
%// Adds a colorbar
So in this example what I would want is middle cell (2,2) to be black. Not the same colour as the maximum value of 7 in the bottom left hand corner (3,1).

Answers (1)

Walter Roberson
Walter Roberson on 13 May 2015
infRGB = reshape([0 0 0],1,1,3); %set to RGB triple for desired color for inf values
infimgdata = repmat(infRGB, size(a,1), size(a,2)); %same size as "a" but all the one color
infimg = image(infimgdata, 'alphadata', ~isnan(a)); %transparent where there are nan
infimgpos = get(infimg, 'Position');
test_image = imagesc(a, 'Position', infimgpos, 'alphadata', ~(isnan(a)|isinf(a)));
colormap(jet());
So values of "a" that are infinite or nan are set to drop through to the color underneath. Underneath is the image that is all the color you want for infinite values except that it too is set to show through to underneath it for the locations that are nan. So inf values show through "a" and show the black image placed underneath, and nan values show through "a" and show through the black image underneath too, right through to the background.
  1 Comment
Martin Grunnill
Martin Grunnill on 14 May 2015
The answer above does not quite work. However it did put me on the write track. I came up with following:
a = [1 2 NaN; 4 Inf 6; 7 5 3];
% sample data
infRGB = reshape([0 0 0],1,1,3);
%set to RGB triple for desired color for inf values in this case black
%denoted by [0 0 0].
infimgdata = repmat(infRGB, size(a,1), size(a,2));
%same size as "a" but all the one color
infimg = image(infimgdata, 'alphadata', ~isnan(a));
%plots an image based on 'infimgdata' excludes NaN's therefore making NaN
%values white
hold on
%plot to same figure
test_image = imagesc(a,'alphadata', ~(isnan(a)|isinf(a)));
%plot data
colormap(jet());
colorbar
hold off
% stop plotting to the same figure

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!