私は同じトピックを調査し、この投稿を作成して問題を解決し、いくつかの調整と一般化を行いました。以前の返信の作成者に感謝します。ここに私の一般化されたコードを示します。これは、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.
次の図を取得します。