How to smooth out or fit a surface?

42 views (last 30 days)
I have my data stored in a 44 by 44 matrix. When I plot this data, it has a lot of irregular peaks. I want a smooth surface instead. (I cannot use the cftool since I've got a long loop and cannot do it manually everytime.) Following is the code I'm using but I get an error saying that x and y should be a column matrix. If I remove the fit command line, the whole code runs perfectly fine. Can someone please point out my mistake or suggest changes to this code?
x = 1:44;
y = 1:44;
for i = 1:35
a = xlsread('\\uoa.auckland.ac.nz\engdfs\Homeair.xlsx',strcat('CO',int2str(46*i-18),':','EF',int2str(46*i+25)));
b = fit([x,y,],a,'lowess');
figure;
surf(x,y,b);
axis([0 44 0 44 -50 120]);
fname = sprintf('A%d.png',i);
saveas(gcf,fname);
end

Accepted Answer

Chad Greene
Chad Greene on 20 May 2016
If you have the image processing toolbox you could do a moving average or a moving median filter. Median filters tend to be good at removing lone bad grid points:
b_smooth = medfilt2(b,[5 5]));
performs a 5x5 moving median filter. Similarly you could do a 5x5 moving average:
b_smooth = imfilter(b,fspecial('average',[5 5]));
  3 Comments
Ke Chao
Ke Chao on 22 Aug 2019
Hi, I have a question about this method. Since the window is [5 5], how about first/last 2 cols or rows? Do we need to extrapolate first and then doing moving average here?
Image Analyst
Image Analyst on 26 Aug 2019
From the help for imfilter: "Input array values outside the bounds of the array are assigned the value X. When no padding option is specified, the default is 0." So you can see that when the window goes outside the image, and the center of the window is on the edge of the image or close to it, it assumes that the image is bigger and the value is zero out there. in other words, it does not shrink/crop the window as the window gets closer to the edge of the image.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 20 May 2016
You can do a regression to fit a 2D polynomial surface to it. See John D'Errico's polyfitn: http://www.mathworks.com/matlabcentral/fileexchange/34765-polyfitn My demo of it is attached where I get a smooth background.

Tags

Community Treasure Hunt

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

Start Hunting!