# Forcing positive values when solving system of linear equations

17 views (last 30 days)
Meng Xi Zhu on 15 Dec 2021
Edited: John D'Errico on 15 Dec 2021
For finding the least squared error solution for X for the equation:
Ax = B
I am currently doing:
x = pinv(A) * B
However, in my case, there are negative values for X in the results, which is non desireable.
Is there a way to force X to be all non-negative values when solving the equation Ax = B using preferably SVD?

John D'Errico on 15 Dec 2021
Edited: John D'Errico on 15 Dec 2021
Sorry. PINV does not allow you to constrain the sign of your estimates.
You can use LSQNONNEG, which does allow you to do that, or you can use a tool like LSQLIN (from the optimization toolbox.)
For eample here, A is a 100x7 matri, with rank 5 by design.
A = randn(100,5)*randn(5,7);
rank(A)
ans = 5
b = randn(100,1);
As you can see, A\b gets upset at you, because A is singular.
A\b
Warning: Rank deficient, rank = 5, tol = 5.624565e-13.
ans = 7×1
-0.2175 0.0546 0 0 0.0494 0.0315 0.1426
However lsqnonneg does not yell at you about a singular matrix A, so you may prefer that. But does it explicitly use the SVD? No. It uses an active set strategy, choosing a subset of the unknowns to be non-negative.
lsqnonneg(A,b)
ans = 7×1
0 0 0.0487 0 0.0086 0.0056 0.0697

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!