'Excluding values from surf plot

Suppose we have a surf plot like this:

A = round(peaks,0);
surf(A)

Is there any way to modify the colormap so that it excludes all values in A that are equal to 0, as if they were NaN?

Colouring 0's as white without affecting the rest of the colourmap would be another acceptable solution.



Solution 1:[1]

You mentioned the solution: set all 0s to nan:

A = round(peaks, 0);
A(A==0)=nan;  % in-place logical mask on zero entries
surf(A)
% The same, but with a temporary variable, thus not modifying A
B = A;
B(B==0) = nan;
surf(B)

Results in (R2007a):

enter image description here

If you do not want to modify A or use a temporary variable, you'll need to "cut a hole" in your colour map

A = round(peaks);

unique_vals = unique(A);  % Get the unique values
cmap = jet(numel(unique_vals));  % Set-up your colour map
zero_idx = find(unique_vals==0);  % find 0 index
cmap(zero_idx,:) = 1;  % all ones = white. Nan would make it black

surf(A, 'EdgeColor', 'none')
colormap(cmap)  % Use our colour map with hole

NB: the 'EdgeColor', 'none' pair is used to remove the edges of each patch, such that you don't see a "grid" where the values are 0.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1