This repository has been archived on 2021-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
NC/mp6/Project_6_Maggioni_Claudio/simplexSolve.m

82 lines
2.2 KiB
Mathematica
Raw Normal View History

2020-12-18 14:43:56 +00:00
function [x_B,c_B,index_B] = simplexSolve(type, B, D, c_B, c_D, h, x_B, ...
x_D, index_B, index_D, itMax)
% Solving a maximization problem with the simplex method
% Initialize the number of iterations
nIter = 0;
% Compute B^{-1}*D and B^{-1}*h
BiD = B\D;
Bih = B\h;
% Compute the reduced cost coefficients
r_D = c_D - (c_B * BiD);
% the optimality condition is satisfied if all
% reduced cost coefficients are positive or negative (depending on the
% problem)
tol = max(size(r_D));
% Check the optimality condition, in order to skip the loop if the
% solution is already optimal
2020-12-19 22:27:43 +00:00
optCheck = typeCond(type, sum(r_D < 0), sum(r_D > 0));
2020-12-18 14:43:56 +00:00
while optCheck ~= tol
% Find the index of the entering variable
2020-12-19 22:27:43 +00:00
idxIN = find(r_D == typeCond(type, max(r_D), min(r_D)));
2020-12-18 14:43:56 +00:00
in = D(:,idxIN);
c_in = c_D(1,idxIN);
index_in = index_D(1,idxIN);
% Evaluate the coefficients ratio for the column corresponding to
% the entering variable
2020-12-19 22:27:43 +00:00
ratio = Bih ./ BiD(:,idxIN);
2020-12-18 14:43:56 +00:00
% Find the smallest positive ratio
2020-12-19 22:27:43 +00:00
idxOUT = find(ratio == min(ratio(ratio > 0)));
2020-12-18 14:43:56 +00:00
out = B(:,idxOUT);
c_out = c_B(1,idxOUT);
index_out = index_B(1,idxOUT);
2020-12-19 22:27:43 +00:00
% Update the matrices by exchanging the columns
2020-12-18 14:43:56 +00:00
B(:,idxOUT) = in;
D(:,idxIN) = out;
c_B(1,idxOUT) = c_in;
c_D(1,idxIN) = c_out;
index_B(1,idxOUT) = index_in;
index_D(1,idxIN) = index_out;
% Compute B^{-1}*D and B^{-1}*h
BiD = B\D;
Bih = B\h;
% Compute the reduced cost coefficients
r_D = c_D - (c_B * BiD);
% Check the optimality condition, in order to exit the loop if the
% solution is already optimal
2020-12-19 22:27:43 +00:00
optCheck = typeCond(type, sum(r_D < 0), sum(r_D > 0));
2020-12-18 14:43:56 +00:00
% Detect inefficient looping if nIter > total number of basic solutions
nIter = nIter + 1;
if nIter > itMax
error('Incorrect loop, more iterations than the number of basic solutions');
end
% Compute the new x_B
x_B = Bih - BiD * x_D;
end
end
function x = typeCond(type, ifMaximum, ifMinimum)
if strcmp(type, 'max')
x = ifMaximum;
elseif strcmp(type, 'min')
x = ifMinimum;
else
error('Incorrect type specified. Choose either a maximisation (max) or minimisation (min) problem.')
end
end