Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB pcolor/surf bilinear interpolation (shading interp)

Consider the following MATLAB code:

C = [ 0 0 0 0 0
      0 1 2 1 0
      0 2 4 2 0
      0 1 2 1 0
      0 0 0 0 0 ];
pcolor( C );
shading interp;
axis square

Note that C is invariant under 90 degree rotations. Also note this sentence from the help for pcolor:

With shading interp, each cell is colored by bilinear interpolation of the colors at its four vertices, using all elements of C.

However, the plotted image is as follows:

CodeOutput

Note that the image is not invariant under 90 degree rotations (consider e.g. the four corners). Now, unless I horribly misunderstand bilinear interpolation, this must be wrong. MATLAB seems to be interpolating on triangles, which is not the same as bilinear interpolation.

Is there any way of working round this MATLAB bug, and getting correct bilinear interpolation? (Other than manually interpolating additional points myself, which still would not cure the issue if one zoomed in far enough.)

like image 312
cfp Avatar asked Nov 18 '17 15:11

cfp


1 Answers

I remember having read a few threads concerning this weird behavior in the official Matlab forums, in the past. Unfortunately, I found none right now with a quick search. Anyway... you aren't the first used pointing out that shading interp, used in combination with with pcolor, behaves in a weird manner, creating shapes that don't reflect the underlying data.

The main problem is that shading interp interpolates between data points without caring about how sensible your grid is to smoothing. If you want a result that doesn't look jagged, you have to provide data sampled at a higher resolution:

C = [
    0 0 0 0 0
    0 1 2 1 0
    0 2 4 2 0
    0 1 2 1 0
    0 0 0 0 0
];
C = interp2(C,5,'cubic');

pcolor(C);
shading interp;
axis square;

This produces an amazing result, and the output doesn't show any artifact or asymmetry:

Output

like image 197
Tommaso Belluzzo Avatar answered Oct 24 '22 09:10

Tommaso Belluzzo