Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove base line drift with peicewise cubic spline algorithm using MATLAB

I have a signal which I want to remove the basline drift using the picewise cubic spline algorithm in MATLAB.

 d=load(file, '-mat');



 t=1:length(a);

 xq1=1:0.01:length(a);
  p = pchip(t,a,xq1);
  s = spline(t,a,xq1);
    % 
 figure, hold on, plot(a, 'g'), plot(t,a,'o',xq1,p,'-',xq1,s,'-.')
 legend('Sample Points','pchip','spline','Location','SouthEast')

But I cant see any basline removal..The orginal data is exactly on the interpolated one.Displayed plot

or in the other signal as we can see no base line is removed. plot2

The question is how I can "use peicewise cubic spline interpolation to remove basline drift" in MATLAB.

Thank you

like image 526
Juliette Avatar asked Aug 30 '17 20:08

Juliette


2 Answers

It seems likely that you are looking to fit a polynomial to your data to estimate baseline drift due to thermal variations. The problem with spline is that it will always perfectly fit your data (similar to pchip) because it is an interpolation technique. You probably want a courser fit which you can get using polyfit. The following code sample shows how you could use polyfit to estimate the drift. In this case I fit a 3rd-order polynomial.

% generate some fake data
t = 0:60;
trend = 0.003*t.^2;
x = trend + sin(0.1*2*pi*t) + randn(1,numel(t))*0.5;

% estimate trend using polyfit
p_est = polyfit(t,x,3);
trend_est = polyval(p_est,t);

% plot results
plot(t,x,t,trend,t,trend_est,t,x-trend_est);
legend('data','trend','estimated trend','trend removed','Location','NorthWest');

Update

If you have the curve fitting toolbox you can fit a cubic spline with an extra smoothing constraint. In the example above you could use

trend_est = fnval(csaps(t,x,0.01),t);

instead of polyfit and polyval. You will have to play with the smoothing parameter, 0 being completely linear and 1 giving the same results as spline.

enter image description here

like image 188
jodag Avatar answered Sep 28 '22 14:09

jodag


I think you should reduce the number of points at which you calculate the spline fit (this avoids over-fitting) and successively interpolate the fit on the original x-data.

t = 0:60;
trend = 0.003*t.^2;
x = trend + sin(0.1*2*pi*t) + randn(1,numel(t))*0.5;

figure;hold on
plot(t,x,'.-')

%coarser x-data
t2=[1:10:max(t) t(end)]; %%quick and dirty. I probably wanna do better than this
%spline fit here
p = pchip(t,x,t2);
s = spline(t,x,t2);
plot(t2,s,'-.','color' ,'g')

%interpolate back
trend=interp1(t2,s,t);

%remove the trend
plot(t,x-trend,'-.','color' ,'c')

result

like image 44
shamalaia Avatar answered Sep 28 '22 14:09

shamalaia