For a given matrix, return the determinant and the permanent of the matrix.

The determinant is given by

 



det
(
A
)
=

∑

σ


sgn
⁡
(
σ
)

∏

i
=
1


n



M

i
,

σ

i






{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}


while the permanent is given by

 



perm
⁡
(
A
)
=

∑

σ



∏

i
=
1


n



M

i
,

σ

i






{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}


In both cases the sum is over the permutations 



σ


{\displaystyle \sigma }

 of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)

More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.



Related task

 Permutations by swapping


real vector range1(real scalar n, real scalar i) {
	if (i < 1 | i > n) {
		return(1::n)
	} else if (i == 1) {
		return(2::n)
	} else if (i == n) {
		return(1::n-1)
	} else {
		return(1::i-1\i+1::n)
	}
}
 
real matrix submat(real matrix a, real scalar i, real scalar j) {
	return(a[range1(rows(a), i), range1(cols(a), j)])
}
 
real scalar sumrec(real matrix a, real scalar x) {
	real scalar n, s, p
	n = rows(a)
	if (n==1) return(a[1,1])
	s = 0
	p = 1
	for (i=1; i<=n; i++) {
		s = s+p*a[i,1]*sumrec(submat(a, i, 1), x)
		p = p*x
	}
	return(s)
}