How to smooth 2d matrix
112 views (last 30 days)
Show older comments
I have 2d matrix. size is give below. I want to smooth this but smooth function is not working properly with imagesc. please help me. Thank you in advance
[ch] = imagesc(all_time,height,smooth(data,1000));
all_time = 30509x1
height = 533x1
data = 533x30509
0 Comments
Answers (2)
Walter Roberson
on 29 May 2016
smooth() is only defined for a vector argument. Internally it reshapes the input to a column vector. If you want to smooth column by column, you will need to do that in a loop before you display the data.
Kristoffer Walker
on 21 Jul 2020
Use the ":" operator to convert the matrix to a vector, use smooth() to smooth, and return the content to the original matrix format again using ":" operator. For example
A=[0 0 0; 0 0 0; 0 1 0; 0 0 0 ; 0 0 0]
A(:) = smooth(A(:),3)
No need for fancy conv2, filter, or other commands.
Kris
1 Comment
Christian Ballesteros
on 10 May 2021
Edited: Christian Ballesteros
on 10 May 2021
This way you are not accounting for the effect of side-by-side (columns) samples and you smooth last data of a column with the beginning of the following one, which might not be correlated at all. A proper matrix smoothing requires a 2D filtering window.
Example:
% Input data
[P,T] = meshgrid(0:359,0:180);
A = awgn(sind(T).*cosd(P),5); % My matrix to smooth
w = 5; % Size of the sliding window (same number of cols and rows in this case)
% Extrapolate values for current window
[Nr,Nc] = size(A);
Nextra = 0.5*(w-1);
Ap = interp2(1:Nc,1:Nr,A,-Nextra+1:Nc+Nextra,(-Nextra+1:Nr+Nextra).','makima'); % 2D extrapolation must use 'spline' or 'makima' interpolation
% Smooth data with sliding window
H = ones(w)./w^2; % The 2D averaging filter
B = filter2(H,Ap,'valid'); % The smooth resulting matrix
% Visualize data
figure; pcolor(A); caxis([-1 1]); shading interp;
figure; pcolor(B); caxis([-1 1]); shading interp;
See Also
Categories
Find more on Smoothing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!