Search code examples
c++matrixarmadillo

Best way to broadcast Armadillo matrix operations similar to Numpy


Consider the matrices A and B where A is a 5x5 matrix and B is a 1x5 matrix (or a row vector). If I try to do A + B in Numpy, its broadcasting capabilities will implicitly create a 5x5 matrix where each row has the values of B and then do normal matrix addition between those two matrices. This can be written in Armadillo like this;

mat A = randu<mat>(4,5);
mat B = randu<mat>(1,5);
A + B;

But this fails. And I have looked at the documentation and couldn't find a built-in way to do broadcasting. So I want to know the best (fastest) way to do an operation similar to the above.

Of course, I could manually resize the smaller matrix into the size of the larger, and copy the first-row value to each other row using a for loop and use the overloaded + operator in Armadillo. But, I'm hoping that there is a more efficient method to achieve this. Any help would be appreciated!


Solution

  • Expanding on the note from Claes Rolen. Broadcasting for matrices in Armadillo is done using .each_col() and .each_row(). Broadcasting for cubes is done with .each_slice().

    mat A(4, 5, fill::randu);
    
    colvec V(4, fill::randu);
    rowvec R(5, fill::randu);
    
    mat X = A.each_col() + V;  // or A.each_col() += V for in-place operation
    mat Y = A.each_row() + R;  // or A.each_row() += R for in-place operation
    
    cube C(4, 5, 2, fill::randu);
    cube D = C.each_slice() + A;  // or C.each_slice() += A for in-place operation