%------------------------------------------------
% 2011/01/02 version 1.0
%
% [xxx, yyy] = LatexFilter(x, y, tol)
%
% This function may be used before exporting data to latex for intelligent
% filtering.
% If you want to plot data with NumericPlots one problem might be that you
% have to plot way to many points and get an TexCapacityExceeded-Error. One
% way to address this is this filter. Given x- and y-data and a tolerance
% tol, unnecessary data may be removed without changing the look of your
% plot.
% Example:
% x=[1 2 3 4 5 6 7 8 9 10];
% y=[0.01 -0.01 0.02 0.04 -0.03 100.03 100.01 99.97 99.98 100.01];
% [a b] = LatexFilter(x,y, 0.5)
% returns
% a = 1     5     6    10
% b = 0.0100   -0.0300  100.0300  100.0100
% thus preserving the step from 0 to 100 at x=5 but removing the 'noise'.
%------------------------------------------------
% output:
%  xxx, yyy: filtered data
% input:
%  x, y: data to be filtered
%  tol: tolerance

% author: Thomas Koenig
% date: 2011/01/02
%
% Copyright 2010 Thomas König, Alexander Michel
%
% This file is part of NumericPlots.
%
% NumericPlots is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% any later version.
% 
% NumericPlots is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with NumericPlots.  If not, see <http://www.gnu.org/licenses/>.

function [xxx, yyy] = LatexFilter(x, y, tol)

% fprintf('LatexFilter: Input - %i ...', length(x));

xx = zeros(size(x));
yy = zeros(size(y));
xx(:,1) = x(:,1);
yy(:,1) = y(:,1);
k = 1;
LastI = 1;
for i=2:length(x)-1
    if max(abs(y(:,i) - yy(:,k)))>tol
        if LastI<i-1
            k=k+1;
            xx(:,k) = x(:,i-1);
            yy(:,k) = y(:,i-1);
        end
        k=k+1;
        xx(:,k) = x(:,i);
        yy(:,k) = y(:,i);    
    end
end
k = k+1;
xx(:,k) = x(:,i+1);
yy(:,k) = y(:,i+1);

xxx = xx(:,1:k);
yyy = yy(:,1:k);

% fprintf(' Output - %i .\n', length(xxx));
        
end