```⍝ Determinant of square matrix:

det 2 2⍴2 3 4 5
¯2
det 1 1⍴3
3
det 0 0⍴7
1
hil←{÷1+∘.+⍨(⍳⍵)-⎕io}       ⍝ Order-⍵ Hilbert matrix.

det hil 5
3.749295133E¯12

det_rh4a←{⎕io ⎕ml←0         ⍝ Gauss-Jordan
⍺←1                     ⍝ product of diagonal entries so far
p←{⍵⍳⌈/⍵}|⍵[;0]         ⍝ index of pivot row
p=n:0                   ⍝ ⍵ is singular if column is all 0
k←⍳n                    ⍝ row indices
k[⌽i]←k[i←(×p)/p,0]     ⍝ interchange p and 0, if different
(⍺×d×¯1*×p)∇ ⍵[1↓k;1↓⍳n]-(⍵[1↓k;0]÷d←⍵[⊃k;0])∘.×⍵[⊃k;1↓⍳n]
}

det_rh4a hil 5
3.749295133E¯12

detG←{                                  ⍝ Gaussian determinant.
(⎕IO ⎕ML)←1 3 ⋄ r←⍴⍵
1≥×/r:↑⍵ ⋄ 2≠⍴r:0 ⋄ ≠/r:0           ⍝ check for trivial cases
1{                                  ⍝ inner loop
2>↑⍴⍵:↑⍺×⍵                      ⍝ end? -> result
(m a c)←{                       ⍝ calculate matrix, anchor & coeff
0≠1⍴⍵:⍵(1⍴⍵)1               ⍝ default: original matrix
z←⍵ ⋄ j←{⍵⍳⌈/⍵}|z[;1]       ⍝ look for 1st non-zero
z[1,j;]←z[j,1;]             ⍝ reorder matrix
z(1⍴z)¯1                    ⍝ NB. coeff=¯1
}⍵
a=0:0                           ⍝ row of zeroes..
(⍺×a×c)∇ 1 1↓m-m[;1]∘.×m[1;]÷a  ⍝ re-curses!
}⍵
}

detG hil 5
3.749295133E¯12

det_mv←{        ⍝ Matrix determinant, based on Mahajan-Vinay algorithm:

⍝|  Meena Mahajan and V Vinay.
⍝|   Determinant: Combinatorics, Algorithms, and Complexity
⍝|    http://www.imsc.ernet.in/~meena/publ.html

(⎕IO ⎕ML)←0 3 ⋄ mat←⍵ ⋄ n←↑⍴mat
V←(2,3/n)⍴0 ⋄ V[2|n;;;0]←1

↑{i←⍵
↑{v←⍵
↑{u←⍵ ⋄ n=⍵+1:0
↑{
V[0;u;⍵;i+1]+←V[0;u;v;i]×mat[v;⍵]
V[1;⍵;⍵;i+1]+←V[0;u;v;i]×mat[v;u]
V[1;u;⍵;i+1]+←V[1;u;v;i]×mat[v;⍵]
V[0;⍵;⍵;i+1]+←V[1;u;v;i]×mat[v;u]
0
}¨(⍵+1)↓⍳n
}¨⍳⍵+1
}¨⍳n
}¨⍳n-1:

+/{-+/mat[⍵;⍳⍵+1]×-⌿V[;⍳⍵+1;⍵;n-1]}¨⍳n
}

det_mv hil 4
1.653439153E¯7

detriment←{∇{⍵+(¯1*+/∧\⍺)×⍵⍵[⎕io;⍺⍳0]×⍺⍺ ⍺/1 0↓⍵⍵}⍵/(↓≠/¨⍳⍴⍵),0 0≡⍴⍵}

detriment hil 4
1.653439153E¯7

dd ← 2 2⍴ 0 1, 1 0

det dd
¯1
det_rh4a dd
¯1
det_mv dd
¯1
detG dd
¯1
detriment dd
¯1

Back to: code

Back to: Workspaces
```