%% Convolution Filter to Smooth Data
% This example shows how to use a convolution filter to remove
% high-frequency components from a matrix to smooth the matrix for contour
% plotting.
%
% The |conv2| and |filter| functions can
% remove high-frequency components from a matrix representing a continuous
% surface or field to make the underlying data easier to visualize.
%
% Create a function of two variables and plot the contour lines at a
% specified, fixed interval.

% Copyright 2015 The MathWorks, Inc.


Z = peaks(100);
clevels = -7:1:10; % contour levels for all plots

figure
contour(Z,clevels)
axis([0,100,0,100])
title('Peaks Surface (underlying data)')

%%
% Add uniform random noise with a mean of zero to the surface and plot the
% resulting contours. Irregularities in the contours tend to obscure the
% trend of the data.

ZN = Z + rand(100) - .5;

figure
contour(ZN,clevels)
axis([0,100,0,100])
title('Peaks Surface (noise added)')

%%
% Specify a 3-by-3 convolution kernal, |F|, for smoothing the matrix and use
% the |conv2| function to attenuate high spatial frequencies in the surface
% data. Plot the contour lines.
F = [.05 .1 .05; .1 .4 .1; .05 .1 .05];
ZC = conv2(ZN,F,'same');

figure
contour(ZC, clevels)
axis([0,100,0,100])
title('Noisy Surface (smoothed once)')

%%
% Smooth the surface one more time using the same operator and plot the
% contour lines. A larger or more uniform kernal can achieve a smoother
% surface in one pass.

ZC2 = conv2(ZC,F,'same');

figure
contour(ZC2, clevels)
axis([0,100,0,100])
title('Noisy Surface (smoothed twice)')
