Search code examples
recursionscilabdeterminants

Why doesn't this Scilab program of finding the determinant recursively work?


I am trying to find the determinant of an $N\timesN$ matrix. Here's my code:

clc
function determinant=take_detm(A)
order=sqrt(length(A))
disp(order)
if order==2 then 
    determinant=A(1,1)*A(2,2)-A(1,2)*A(2,1);

else

    s=0
    for i=1:order
        s=s+((-1)^(i+1))*A(1,i)*take_detm(A(:,i)=[]);//deleting 1st row and a column in the recursive call
    end
    determinant=s

end
endfunction
matr=input("Enter a matrix")
printf (string(take_detm(matr)))

Here's the problem: When I run the code and input a matrix as: [1 2 3 4;5 6 7 8;9 10 11 12;13 14 15 16] the console prints 4 (the order) and the program hangs. I get that rolling blue ring of Windows 7 and after some time a message which says that Scilab 6.0.1 has stopped working. Is there any issue with the algorithm or is it something else? PS-Beginner level


Solution

  • The problem is due to the A(:,i)=[] instruction. assigning [] only works for a set of full rows or a set of full lines, so your instruction simply removed the ith column of the A matrix (the result being a rectangular matrix)

    You can fix the problem with

        Ai=A(2:order,[1:i-1 i+1:order])//deleting 1st row and  column i
        s=s+((-1)^(i+1))*A(1,i)*take_detm(Ai); //recursive call
    

    Note however that the Scilab det function is much more precise and efficient