diff --git a/mat/diagonal.go b/mat/diagonal.go index f3357d6b..f7247170 100644 --- a/mat/diagonal.go +++ b/mat/diagonal.go @@ -5,6 +5,8 @@ package mat import ( + "math" + "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/blas/blas64" ) @@ -324,3 +326,25 @@ func (d *DiagDense) Trace() float64 { return tr } + +// Norm returns the specified norm of the receiver. Valid norms are: +// 1 or Inf - The maximum diagonal element magnitude +// 2 - The Frobenius norm, the square root of the sum of the squares of +// the diagonal elements +// +// Norm will panic with ErrNormOrder if an illegal norm is specified and with +// ErrZeroLength if the receiver has zero size. +func (d *DiagDense) Norm(norm float64) float64 { + if d.IsEmpty() { + panic(ErrZeroLength) + } + switch norm { + default: + panic(ErrNormOrder) + case 1, math.Inf(1): + imax := blas64.Iamax(d.mat) + return math.Abs(d.at(imax, imax)) + case 2: + return blas64.Nrm2(d.mat) + } +} diff --git a/mat/matrix.go b/mat/matrix.go index 71e1e823..dd7750a5 100644 --- a/mat/matrix.go +++ b/mat/matrix.go @@ -44,6 +44,7 @@ type allMatrix interface { type denseMatrix interface { DiagView() Diagonal Tracer + Normer } var (