%MATLAB code to pivot on a dictionary
%Usage:
%Set up:
%Specify...
%   an mxn matrix, A, of constraint coeffs.
%   an mx1 matrix, b, of RHS values (assumed >=0)
%   a 1xn matrix, c, of objective fn coeffs.
%   and an initial value z (the objective value), usually zero.
%   There are three MATLAB functions to be used with these definitions
%   dict() prints the current A, b, c, z in dictionary format
%   ratios(j) determines all upper bounds for entering variable xj.
%   lppivot(i,j) modifies A, b, c, z by pivoting on eqn i, variable j
%   Define A, b, c, z in the space indicated, then run this script. The
%   three functions dict, ratios, and lppivot can then be used.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Contents of lppivot.m

function lppivot(leave, enter)
%lppivot(i, j) modifies A, b, c, z by pivoting on eqn i, variable j
global A b c m n z bas nonbas
 
if isempty(find(bas==leave))
    error('Error (lppivot): The chosen exiting variable x%d is NOT basic.\n',leave)
end
 
pivcol = find(nonbas==enter);
pivrow = find(bas==leave);
if A(pivrow,enter) == 0
    error('Error (lppivot): Division by zero.')
end
b(pivrow,1)=b(pivrow,1)/A(pivrow,enter);
for i=1:n
    if ~isempty(find(nonbas==i)) && i~=enter
    A(pivrow,i)=A(pivrow,i)/A(pivrow,enter);
    end
end
tempcol = A(1:m,leave);
%temp = A(pivrow, leave);
A(pivrow, leave) = 1/A(pivrow, enter);
%A(pivrow, enter) = temp;
 
for i=1:m
    if i~=pivrow
    b(i,1)=b(i,1)-A(i,enter)*b(pivrow,1);
    for j=1:n
        if ~isempty(nonbas==j) && j~=enter
        A(i,j)=A(i,j)-A(i,enter)*A(pivrow,j);
        end
    end
    A(i,leave)=-A(pivrow,leave)*A(i,enter);
    end
end
z=z+c(1,enter)*b(pivrow,1);
for i=1:n
    if ~isempty(nonbas==i) && i ~= enter
        c(1,i)=c(1,i)-A(pivrow, i)*c(1,enter);
    end
end
c(1,leave)=-c(1,enter)*A(pivrow,leave);
c(1,enter)=0;
temp = bas(1,pivrow);
bas(1,pivrow)=nonbas(1,pivcol);
nonbas(1,pivcol)=temp;
for i=1:m
    A(i,enter) = tempcol(i,1);
end
dict()
end


