sgorsten / linalg

linalg.h is a single header, public domain, short vector math library for C++
The Unlicense
854 stars 68 forks source link

Reduction functions for matrices? #10

Closed wojdyr closed 6 years ago

wojdyr commented 7 years ago

I just tried to call argmax() with a matrix as an argument and realized that the reductions here work only for vectors.

So here is a feature request to consider: functions such as sum() and argmax() for matrices.

sgorsten commented 7 years ago

Extending the fold functions over matrices shouldn't be too hard.

argmax() is a trickier case. I've painted myself into a bit of a consistency corner. maxelem(a) is defined as a[argmax(a)] for vectors, there's a nice symmetry between argmax returning an int and operator[] taking an int. argmax on a matrix COULD return the index of the "greatest" column, as linalg::vec does model LessThanComparable, but this seems a little nonsensical and not very useful. A matrix is semantically quite a bit different from a sequence of vectors.

argmax could return the index of the greatest element as though the matrix were a flat array in column major order. I do define a few other operations on matrices (comparison ops, etc.) as though they were a flat sequence of numbers, but I don't have any sort of function for "flat indexing" into a linalg::mat.

I suppose argmax could return an int2, and I could add an overload of operator[] which accepts an int2. The only remaining question is whether mat[{x,y}] should be equal to mat[x][y] (less confusing) or mat[y][x] which would match the sort of "row,column" subscripting you see in math textbooks.

I'll do the fold functions right away, and I welcome your input on what would be most logical for something like argmax.

sgorsten commented 6 years ago

I'm going to close this issue for now, as the obvious improvements were made and there was no further input on the argmax semantics.