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


#!/usr/bin/perl
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;
 
sub permanent{
	my $mat = shift;
	my $n = shift // $mat->dim(0);
	return undef if $mat->dim(0) != $mat->dim(1);
	return $mat(0,0) if $n == 1;
	my $sum = 0;
	--$n;
	my $m = $mat(1:,1:)->copy;
	for(my $i = 0; $i <= $n; ++$i){
		$sum += $mat($i,0) * permanent($m, $n);
		last if $i == $n;
		$m($i,:) .= $mat($i,1:);
	}
	return sclr($sum);
}
 
my $M = pdl([[2,9,4], [7,5,3], [6,1,8]]);
print "M = $M\n";
print "det(M) = " . $M->determinant . ".\n";
print "det(M) = " . $M->det . ".\n";
print "perm(M) = " . permanent($M) . ".\n";