%mathpiper,def="Sparsity"

Function("Sparsity",{matrix})
[
	Local(rows,cols,nonzero);
	nonzero:=0;
	rows:=Length(matrix);
	cols:=Length(matrix[1]);
	ForEach(i, 1 .. rows )
		ForEach(j, 1 .. cols )
			If(matrix[i][j] != 0, nonzero:=nonzero+1 );

	N(1 - nonzero/(rows*cols));
];

%/mathpiper



%mathpiper_docs,name="Sparsity",categories="User Functions;Linear Algebra"
*CMD Sparsity --- get the sparsity of a matrix
*STD
*CALL
	Sparsity(matrix)
*PARMS

{matrix} -- a matrix

*DESC

The function {Sparsity} returns a number between {0} and {1} which 
represents the percentage of zero entries in the matrix. Although
there is no definite critical value, a sparsity of {0.75}  or more
is almost universally considered a "sparse" matrix. These type of
matrices can be handled in a different manner than "full" matrices
which speedup many calculations by orders of magnitude.

*E.G.

In> Sparsity(Identity(2))
Result: 0.5;
In> Sparsity(Identity(10))
Result: 0.9;
In> Sparsity(HankelMatrix(10))
Result: 0.45;
In> Sparsity(HankelMatrix(100))
Result: 0.495;
In> Sparsity(HilbertMatrix(10))
Result: 0;
In> Sparsity(ZeroMatrix(10,10))
Result: 1;
%/mathpiper_docs