为什么此Scilab程序递归查找行列式不起作用?

时间:2018-11-19 13:40:51

标签: recursion scilab determinants

我试图找到$ N \ timesN $矩阵的行列式。这是我的代码:

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)))

这是问题所在:当我运行代码并输入矩阵为:[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]控制台将打印4(顺序)和程序挂。我得到Windows 7滚动的蓝圈,一段时间后出现一条消息,提示Scilab 6.0.1已停止工作。算法是否存在问题或其他问题? PS入门级

2 个答案:

答案 0 :(得分:0)

该问题归因于A(:,i)= []指令。分配[]仅适用于一组完整的行或一组完整的行,因此您的指令只需删除A矩阵的第i列(结果是矩形矩阵)

您可以使用

解决问题
    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

但是请注意,Scilab det函数更加精确和高效

答案 1 :(得分:0)

好的,所以我有把握得到这个,因此回答了我自己的问题。

要在Scilab中删除行 OR 时,可以将其分配给[]。下面的示例说明了它是如何工作的。 考虑矩阵

A=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]

其在控制台中的显示方式为

A  = 

   1.    2.    3.    4. 
   5.    6.    7.    8. 
   9.    10.   11.   12.
   13.   14.   15.   16.

如果要删除第一行,则命令为

    A(1,:)=[]
 A  = 

   5.    6.    7.    8. 
   9.    10.   11.   12.
   13.   14.   15.   16.

您只需将第一行分配给空矩阵。同样,如果要删除第二列,则将其分配给空矩阵:

A(:,2)=[]
A  = 

   5.    7.    8. 
   9.    11.   12.
   13.   15.   16. 

(请注意,该操作是在更新后的矩阵上执行的-即删除了第一行) 但是,如果要删除第一行和第二列,则不能编写:

A(1,2)=[]

Scilab说:

Submatrix incorrectly defined.

这是使用分配给空矩阵的替代解决方案: 总体思路:我们一个接一个地执行2个操作:删除第一行,然后删除第i列。 仅在 else 部分发布代码:

else

    s=0
    first_row_removed=A //taking a backup of A and then...
    first_row_removed(1,:)=[] //...removing the 1st row
    for i=1:order
        column_i_removed=first_row_removed //taking a backup of the 1st-row-removed matrix...
        column_i_removed(:,i)=[] //... and then deleting column i
        s=s+((-1)^(i+1))*A(1,i)*take_detm(column_i_removed); //recursive call
    end
    determinant=s

end //of else   

要注意的重要一点是,执行对空矩阵的分配会更改原始矩阵本身。因此,对于for循环的每次迭代,我们必须确保对第1行删除的矩阵而不是在先前的for循环迭代中删除了ith列的矩阵上执行remove-ith-column操作。 因此,线

column_i_removed=first_row_removed

必须在for循环内。