MATLAB: Help me in solving Overdetermined Linear LeastSquares solution of AX=B with constraint that every element of column matrix B >0 (B[i]>0)

least square solutionlinear algebramathematicsnumerical solutionoverdetermined system

X=A\B would give least square solution for an overdetermined linear system,e.g I have three variables (x,y,z) with 20 equation so A is a rectangular 20×3 matrix and B is 20×1 constant column matrix. But I have a constraint where the all elements of B[i]( [B]>0). But when solving by least square using A\B solutions are X={a,b,c} such that when I again calculate A*X (=Bcal, calculated value of RHS) to check with actual B(experimental), few Bcal elements are negative. So I need a solution in MATLAB Is it possible to put a constraint such that the X are optimized in such a way in the Least Square so that all the elements Bcal(=A*X)>0 or say any other constraint {where the solution elements of X are to be optimized along with least error/residuals} as per constraint..

Best Answer

X = lsqlin(A,B,-A,zeros(size(B)));
(LSQLIN is from the optimization toolbox.) So you solve the linear system A*X=B in a least squares sense, subject to the linear constraints A*X>=0.
This will work, except that your very next agonized question is why are some of my predictions still slightly less than zero? That can happen because of tiny floating point errors, and the negativity can be on the order of the TolCon parameter for lsqlin. I recall the default value for TolCon is 1.e-8. You cannot set that parameter to zero.
A simple solution for this problem will be to choose some value delta, effectively constraining the predictions to lie greater than delta. You can achieve this by the modified call:
X = lsqlin(A,B,-A,zeros(size(B))-delta);