Search code examples
matlabmatrix-multiplicationnormals

3 dimensional matrix multiplication in matlab


I have a normal map of size mxnx3, where each pixel has a normal vector {Nx, Ny, Nz}. I want to rotate each normal vector independently by a rotation matrix. Let R be the rotation matrix of size mxnx3x3, where each pixel has a rotation matrix of size 3x3.

I want to multiply rotation matrix at each pixel to the normal vector to get the rotated normal vectors. I am looking for an optimized way to do the task, as looping over each pixel may not be the best way.

Please help!!


Solution

  • I would try

    res = sum( bsxfun(@times, map, R), 4 );
    

    With map an m-by-n-by-3 normal vectors, and R an m-by-n-by-3-by-3 the rotation per vector.

    Coming to think about it, you might need to use permute

    res = sum( bsxfun(@times, map, permute(R, [1 2 4 3]) ), 4 ); % transposing the vectors
    

    Or, as Harshit put it:

    res = sum( permute( bsxfun(@times, map, R ), [1 2 4 3]), 4 ); % transposing the vectors