Re: Square Matrix Determinant Recursive Algorithm - Help



In article <ef384d7.-1@xxxxxxxxxxxxxxxxxxxxxxx>, "Alex Pupsa" <pupsaa@xxxxxxxxx> wrote:

Can someone help me?

I need to write a recursive function to calculate the determinant of
a square matrix. I'm having trouble because I don't really know how
recursive functions work in Matlab.

It works for 2x2 and 3x3 matrix.

Here's the code:

function f=determ(a,c)
[n,n]=size(a);
if n==2
f=a(1)*a(4)-a(2)*a(3);
else
for i=1:n
for j=1:n
if i==1
v1=i+1:n;
elseif i==n
v1=1:n-1;
else
v1=1:i-1;
v1(i)=i+1;
for k=i+1:n-1
v1(k)=v1(k-1)+1;
end
end
if j==1
v2=j+1:n;
elseif j==n
v2=1:n-1;
else
v2=1:j-1;
v2(j)=j+1;
for k=j+1:n-1
v2(k)=v2(k-1)+1;
end
end
f=c+((-1)^(i+j))*determ(a(v1,v2),c);
end
end
end

In Matlab I use it by typing: determ(matrix,0)

Gosh, am I'm getting soft? Here I am about to help
someone with their homework. The difference is you
have made a valid attempt at doing it. Its even
reasonably close.

The first comment is you need not pass in c. It
gets summed up as you return from determ. If you
want some code to compare to, look at det from
this toolbox:

http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=9577&objectType=FILE

It does the computation symbolically, but using
the same recursive technique.

John


--
The best material model of a cat is another, or preferably the same, cat.
A. Rosenblueth, Philosophy of Science, 1945

Those who can't laugh at themselves leave the job to others.
Anonymous
.



Relevant Pages