Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a matrix is Singular in Matlab

Tags:

matrix

matlab

I use the function below to generate the betas for a given set of guess lambdas from my optimiser.

When running I often get the following warning message:

Warning: Matrix is singular to working precision. In NSS_betas at 9 In DElambda at 19 In Individual_Lambdas at 36

I'd like to be able to exclude any betas that form a singular matrix form the solution set, however I don't know how to test for it?

I've been trying to use rcond() but I don't know where to make the cut off between singular and non singular?

Surely if Matlab is generating the warning message it already knows if the matrix is singular or not so if I could just find where that variable was stored I could use that?

function betas=NSS_betas(lambda,data)

mats=data.mats2'; 
lambda=lambda;
yM=data.y2';
nObs=size(yM,1);
G= [ones(nObs,1) (1-exp(-mats./lambda(1)))./(mats./lambda(1)) ((1-exp(-mats./lambda(1)))./(mats./lambda(1))-exp(-mats./lambda(1))) ((1-exp(-mats./lambda(2)))./(mats./lambda(2))-exp(-mats./lambda(2)))];

betas=G\yM;
r=rcond(G);

end

Thanks for the advice:

I tested all three examples below after setting the lambda values to be equal so guiving a singular matrix

 if (~isinf(G))
  r=rank(G);
  r2=rcond(G);
  r3=min(svd(G)); 
 end

r=3, r2 =2.602085213965190e-16; r3= 1.075949299504113e-15;

So in this test rank() and rcond () worked assuming I take the benchmark values as given below.

However what happens when I have two values that are close but not exactly equal?

How can I decide what is too close?

like image 326
Bazman Avatar asked Oct 21 '12 20:10

Bazman


1 Answers

rcond is the right way to go here. If it nears the machine precision of zero, your matrix is singular. I usually go with:

if( rcond(A) < 1e-12 )
    % This matrix doesn't look good
end

You can experiment with a value that suites your needs, but taking the inverse of a matrix that is even close to singular with MATLAB can produce garbage results.

like image 68
dinkelk Avatar answered Oct 02 '22 22:10

dinkelk