Search code examples
javamatrixsubtractionejml

Subtract 1 x M matrix from N x M matrix in ejml


Assuming a 1 x M (A) and N x M (B) SimpleMatrix objects in ejml, is there a simple way to subtract A from B? I was looking for a way to repeat the rows of A to be the size of B, but didn't find the method to do this easily.

SimpleMatrix A = new SimpleMatrix(1, 2);
SimpleMatrix B = new SimpleMatrix(2, 2);

A.set(1.0);

B.setRow(0, 0, 2.0, 2.0);
B.setRow(1, 0, 4.0, 4.0);

// Throws java.lang.IllegalArgumentException
// The 'a' and 'b' matrices do not have compatible dimensions
SimpleMatrix C = B.minus(A);

// Expecting
// 1 1
// 3 3

Many answers using matlab (here and here), but I couldn't find a simple syntax for ejml.


Solution

  • According to docs:

    Will concat A and B along their columns and then concat the result with C along their rows. [A,B;C]

    So you could define an equation which will construct a matrix from repeated rows with like (I don't know the N value of B matrix):

    A.equation("A = [A,A,A]")
    

    or

    A.equation("A = [A,A,A]", "A")
    

    The other option is to use SimpleBase.concatColumns(SimpleBase...), it looks like this:

    A = A.concatColumns(A,A)
    

    Assuming A is 1xM it will produce 3xM matrix and store it in A. If you desire to construct such array dynamically you could just concatenate "A," N times (without trailing coma of course) or pass N - 1 times matrix A to function.

    UPDATE

    Sorry, its late I wrongly assumed A is row vector, as it is column vector use comas instead of semicolons, as described in docs.