function x=tridiag(a,b,c,R) 

%  solve  [   a1  b1  0   0          ] [ x1 ]  =  [ R1 ]
%         [   c1  a2  b2  0          ] [ x2 ]     [ R2 ]
%         [   0   c2  a3  b3         ] [ x3 ]     [ R3 ]
%         [   0   0   c3  a4  ....   ] [ x4 ]     [ R4 ]
%         [        :                 ] [  : ]     [  : ]

% a,b,c,R can be given as row or column vectors
% x will be returned as a vector of the same shape as R 

% this is a modified version of the algorithm given in class

n=length(a); 
x=zeros(size(R)); 

if (length(b)==n-1 && length(c)==n-1 && length(R)==n )
   for i=2:n
    fact=c(i-1)/a(i-1);
    a(i)=a(i)-fact*b(i-1);
    R(i)=R(i)-fact*R(i-1);
   end
   x(n)=R(n)/a(n);
   for i=(n-1):(-1):1
     x(i)=(R(i)-b(i)*x(i+1))/a(i);
   end
else
   x=0;   % this will give an error if input sizes don't match
end