Search code examples
matlabplot

Matlab imagesc plotting nan values


When using imagesc to visualize data that contains NaN values, Matlab treats them as the minimum value(in gray it paints them black, jet - blue, etc). the jet colormap doesn't contain neither black nor white. is it possible to display the nan values as black/white? for example:

data = [0 0 0 ; .5 .5 .5 ;1 1 1;nan nan nan];

should yield blue-green-red-black strips.

Thanks


Solution

  • I wrote a custom function to display NaN values as see-through, i.e. with an alpha value of 0.

    function h = imagesc2 ( img_data )
    % a wrapper for imagesc, with some formatting going on for nans
    
    % plotting data. Removing and scaling axes (this is for image plotting)
    h = imagesc(img_data);
    axis image off
    
    % setting alpha values
    if ndims( img_data ) == 2
      set(h, 'AlphaData', ~isnan(img_data))
    elseif ndims( img_data ) == 3
      set(h, 'AlphaData', ~isnan(img_data(:, :, 1)))
    end
    
    if nargout < 1
      clear h
    end
    

    The NaNs will thus be displayed the same colour as the figure background colour. If you remove the line axis image off, then the NaNs will be shown the same colour as the axis background colour. The function assumes the input images are of size n x m (single channel) or n x m x 3 (three channels), so may need some modification depending on your use.

    With your data:

    data = [0 0 0 ; .5 .5 .5 ;1 1 1;nan nan nan];
    imagesc2(data);
    axis on
    set(gca, 'Color', [0, 0, 0])
    

    enter image description here