Search code examples
pngoctavematrix-multiplication

Optimal way to multiply 3D matrices in GNU/Octave


We have a 50x50x3 matrix i loaded with imread from a PNG file, made of 0s and 1s (fore/background). The image is to be inked with a given color, a vector c of 1x3 numbers in [0,1] (RGB), resulting in c(k) replacing the 1s in i(:,:,k) (k in [1...3]), and leaving the 0s unchanged. What would be the expression with a minimal computing time to perform this operation (sort of matrix multiplication) on these to variables?


Solution

  • Start by reshaping c to be a 1x1x3 array:

    c = reshape(c,1,1,3);
    

    Next, do a point-wise multiplication. Octave (as does the newest MATLAB) does implicit singleton expansion (aka broadcasting):

     i = i .* c;