lessthanoptimal / ejml

A fast and easy to use linear algebra library written in Java for dense, sparse, real, and complex matrices.
https://ejml.org
552 stars 116 forks source link

Matrix and vector operations (broadcasting) #32

Open mroodschild opened 6 years ago

mroodschild commented 6 years ago

Hi Peter,

I think it would be good, if ejml supports other matrix operations, such as adding or multiplying a vector to an entire matrix, for example:

[4 5 6]   [1]   [(4+1) (5+1) (6+1)]   [5 6 7]
[1 2 3] + [2] = [(1+2) (2+2) (3+2)] = [3 4 5]
[1 5 9]   [3]   [(1+3) (5+3) (9+3)]   [4 8 12]

or

[4 5 6]             [(4+1) (5+2) (6+3)]   [5 7 9]
[1 2 3] + [1 2 3] = [(1+1) (2+2) (3+3)] = [2 4 6]
[1 5 9]             [(1+1) (5+2) (9+3)]   [2 7 12]

https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html

Thanks Peter!

lessthanoptimal commented 6 years ago

If something like this was added how would you suggest it be incorporated?

CommonOps.bcAdd(A,B,C);
C = SimpleMatrix.bcAdd(A,B);

I don't like automatically broadcasting if the dimensions don't line up. That can easily lead to a difficult to detect bug. Which I have encountered in python/matlab before.

mroodschild commented 6 years ago

Actually for the broadcasting I have to do:

Z [n x m] = W [n x j] * A [j x m] + B [n x 1]

SimpleMatrix W = new SimpleMatrix(2, 3, true, 1.0, 5, 6, 3, 2, 1);
SimpleMatrix A = new SimpleMatrix(3, 1, true, 1.0, 2, 3);
SimpleMatrix B = new SimpleMatrix(2, 1, true, 0.5, 1);

SimpleMatrix Z = W.mult(A);
Z.print();
for (int i = 0; i < Z.numCols(); i++) {
        Z.setColumn(i, 0, Z.extractVector(false, i).plus(B).getDDRM().getData());
}
Z.print();

but it would be easier if:

Z = W.mult(A).bcAdd(B, false)

where:
   true - broadcasting in rows
   false - broadcasting in columns
lessthanoptimal commented 4 years ago

Did you end up implementing this on your own?

VestOfHolding commented 1 year ago

This seems close enough to my request that I'll bump this. I would also really like to be able to do arithmetic operations on two matrices, not just one scalar value.