I want to find out whether a given matrix is singular or not. It is fairly straightforward to do so for small (3x3 and 4x4) matrices but how do I find the determinant for an arbitrary (nxn) order matrix (I want to pass n as a function parameter).
You can try to do some Gaussian Elimination. After that, once you have a triangular matrix, the determinant is found by multiplying the diagonal.
If all this is kind of obscure to you… you should do some search in the net. Some key words are: Linear Algebra, triangular matrix, Gauss Elimination.
here is a trial concerning gauss elemination. Its matlab code, but should be easyly transfered to C++ or a language of your choice. After calculating the gauss-Matrix multiply - as told by atorres - the diagonal entries. If the result is 0, matrix A might be singular. Beware, gauss-elemination is not suitable for any matrices.
p.s. there might be much better sources for gauss, but it works.
function [gauss,b,x] = fcn_gauss(A,b)
gauss = A;
[r,c] = size(A);
nEquation = r-1;
for (i = 1:nEquation)
count = i;
for (j = nEquation:-1:i)
count = count+1;
if (gauss(i,i) == 0) break; end;
factor = gauss(count,i) / gauss(i,i);
gauss(count, = gauss(count, - factorgauss(i, :);
b(count) = b(count) - factorb(i);
x® = b®/gauss(r,r);
for (i = r-1:-1:1)
value = 0;
for (j = r:-1:1)
value = value+x(j)*gauss(i,j);
x(i) = (b(i)-value)/gauss(i,i);
[This message has been edited by xDigital (edited 03-16-2004).]
hmmm, the editor destroys the format…
hope you can read it anyway. Sorry.
Thanks, people! The Gauss-elimination technique came in quite useful once I got it into my head.
Thanks for the code xDigital. I have ported it to C++ and it works very well.