out = [];
filt = [];
base = ones(size(ecg2));
base2 = ones(size(ecg2));
b=0;
b2 = ecg2(1:4:400);

IPhi = inv(Phi);

for i = 1:(numel(ecg2)/size(Phi,1))
    out = [out, weights.*((IPhi)*ecg2(((i-1)*4+1):(i*4)))];
    
    b= b+sum(ecg2(((i-1)*4+1):(i*4)));
    if(mod(i,100) == 0)
        base(((i-100)*4+1):(i*4)) = base(((i-100)*4+1):(i*4)) * (b/400);
        b=0;
    end
    
    b2(mod(i,100)+1) = sum(ecg2(((i-1)*4+1):(i*4)))/4;
    base2(((i-1)*4+1):(i*4)) = (sum(b2)/100)*ones(4,1);
end

for i = 1:size(out,2)
    filt = [filt, (Phi*(out(:,i)))'];
end
filt=filt';

figure(1),plot(1:1000,out(:,1:1000));
figure(2),hold off,plot(ecg2(1:1000)),hold on,plot(filt(1:1000),'r');
figure(3),hold off,plot(filt(1:1000)-base(1:1000)),hold on, plot(filt(1:1000)-base2(201:1200),'r');