3

What is the best (readable and fast) way to find maximum matrix element using MathNet in C#? This is my way:

int size = 4;
var matrix = Matrix.Build.Dense(size, size, Matrix.One);
matrix[3, 3] = 3;
var max = matrix.ReduceRows((v1, v2) => v1.AbsoluteMaximum() > v2.AbsoluteMaximum()? v1 : v2).AbsoluteMaximum()
Community
  • 1
  • 1
  • 1
    Please define what you mean by `the best way`. The fastest? Least number of characters? Easier to understand? Something else? – Victor Zakharov Nov 09 '15 at 01:33
  • 1
    @Neolisk thanks, I defined "the best way". I believe that every programming language/lib has a default way of doing things that you should adjust only for some performance reasons and so on. In this case, code prioritizes readability over everything else, though performance is still respected. – Ruslan Gunawardana Apr 12 '19 at 10:00

1 Answers1

4

Try matrix.Enumerate().Maximum() instead, that is both much simpler and much faster. You could also use the Enumerable.Max extensions method, but Statistics.Maximum is significantly faster in case of a dense matrix.

For sparse matrices you may want to do matrix.Enumerate(Zeros.AllowSkip).Maximum() instead, although that would need special handling if the returned value is negative (but might have to be zero).

Also note that AbsoluteMaximum is really the absolute maximum, which is different from the maximum (|-5| > |3|, but -5 < 3).

Christoph Rüegg
  • 4,626
  • 1
  • 20
  • 34