from Adaptive-Degree Polynomial Filter (Savitzky-Golay Filter) by Jianwen Luo
Obtain the polynomial degree selected in the adaptive-degree polynomial filter.

adpf_demo.m
global Pkmi_array
if exist('Pkmi_array.mat','file')
    load Pkmi_array
else
    error('Please run Pkmi_Calculate first to obtain the numerical table of gram polynomials!')
end

A=1;
x0s=[20 40 60 90];
ws=[1 2 4 8]*2;
dx=min(ws)/5;

x=0:dx:120;
y=0;
for k=1:length(x0s)
    x0=x0s(k);
    w=ws(k);
    y1=A*exp(-4*log(2)*(x-x0).^2/w^2);    
    y=y+y1;
end

yn=y+randn(size(y))*0.2;

figure
plot(x,y,'r');
hold on
plot(x,yn,'m')
title('data');

m=10;
hs=zeros(2*m,2*m+1);
for deg=1:2*m
    hs(deg,1:2*m+1)=sgsdf_smooth_closed_form(deg,m);
end

degs=[];
y_adpf=[];
for k=m+1:length(yn)-m
    k
    y1=yn(k-m:k+m);
    deg=adpf(y1);
    degs=[degs deg];
    h=hs(deg,:);
    
    y_adpf=[y_adpf block_oper(y1,h)];
end

figure
plot(x,y,'r')
hold on
plot(x(m+1:end-m),y_adpf);
title('adaptive degree')

figure
stem(x(m+1:end-m),degs);
title('polynomial degree');


for deg=1:2:7
    h=hs(deg,:);
    y_smoothed=block_oper(yn,h);
    figure    
    plot(x,y,'r');
    hold on 
    plot(x(m+1:end-m),y_smoothed);
    title(sprintf('polynomial degree = %d',deg));
end

Contact us at files@mathworks.com