% Function plot_approx_linear(x,a,b,K,fun)
% ---------------------------------------------------------------------------
% Plots a function defined by a handle fun and its piecewise linear approximation
% on interval [a,b]. x gives the coefficients of the piece-wise linear
% approximation of the function and K is the number of elements on interval [a,b].
% ---------------------------------------------------------------------------
% 27/09/13 : Pasi Ylä-Oijala - Department of Radio Science and Engineering
% ---------------------------------------------------------------------------

function plot_approx_linear(x,a,b,K,fun)

% the function
xx = linspace(a,b,100);
u  = feval(fun,xx);
plot(xx,u,'-b','linewidth',2)
grid
hold on

% and the approximation
xk = linspace(a,b,K+1);
cp = (xk(2:end)+xk(1:end-1))/2;

for k=1:K                       % loop over the elements
  % approximation is linear on element k
  xx   = [xk(k),cp(k),xk(k+1)];          % three points on interval [x(k),x(k+1)]
  lin1 = (xk(k+1)-xx)./(xk(k+1)-xk(k));  % first part of a linear function
  lin2 =  (xx-xk(k))./(xk(k+1)-xk(k));   % second part of a linear function
  plot(xx,x(k)*lin1+x(k+1)*lin2,'or','linewidth',2)
end
legend('analytical','numerical',1)
hold off
% ---------------------------------------------------------------------------
