我正在研究同一主题,创建了解决我的问题的这篇文章,进行了一些调整和概括。非常感谢之前回复的作者,这是我的通用代码,它也适用于 n 维点向量
% SMOOTH Simple gaussian smooth function
% vector = input vector
% width = width of the smoothing
% window = width of the window to be used in the convolution
%
% Credits: Generalization of a post made by User1551892 and Louis Mendo on
% StackOverflow
% Created by: Leonardo Daga, 2016
function smoothedVector = smooth(vector, width, window)
% Check arguments and fill with defaults
if nargin < 2,
width = 2;
end
if nargin < 3,
window = width * 5 + 1;
end
% Rotate vector to a column vector (if needed) to make the code easier
if size(vector,1) > size(vector,2)
isColumn = true;
else
isColumn = false;
vector = vector';
end
% Construct blurring window.
windowWidthInt = int16(window);
halfWidth = double(windowWidthInt / 2);
gaussFilter = Gaussian(-(halfWidth-1):(halfWidth-1), 0, width/2 ) ;
gaussFilter = gaussFilter / sum(gaussFilter);
% Do the blur, enlarging the vector to blur from the start with a
% convenient value and cutting the vector back when the blurring is done
enlargedVector = [ones(window, 1)*vector(1,:);
vector;
ones(window, 1)*vector(end,:)];
smoothedVector = zeros(size(enlargedVector,1)-1,size(enlargedVector,2));
for i=1:size(vector,2),
smoothedVector(:,i) = conv(enlargedVector(halfWidth:end-halfWidth,i), gaussFilter) ;
end
smoothedVector = smoothedVector(window:end-window,:);
% Rotate back the vector, if it was a row vector
if (isColumn == false)
smoothedVector = smoothedVector';
end
end
%% Create a gaussian vector to be used for the convolution
function y = Gaussian ( window, mu, sigma)
y = exp (-((window - mu).^2)/(2*sigma^2)) ;
end
您可以使用以下示例代码运行此函数:
% Generate sample data.
vector = [5*(1+cosd(1:3:900)) + 2 * rand(1, 300);
5*(1+sind(1:3:900)) + 2 * rand(1, 300)];
smoothedVector = smooth(vector, 5) ;
% plot it.
figure
plot(1:size(vector,2), vector, 'r-', 1:size(smoothedVector,2), smoothedVector, 'b-');
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
得到下图: