Search code examples
matlabmatrixmultiplication

Multiplying each column in matrix by the corresponding row in a vector


I have a 6231x16825 matrix H and a 16825x1 column vector W.

For example, if W = [2; 3; 3 ...]' and H = [1 2 3; 4 5 6 ...], I need to obtain:

prod = [1*2 2*3 3*3; 4*2 5*3 6*3]

How to do this? Thanks


Solution

  • There are many ways possible, choose the one that fits you:

    • Using bsxfun:

      res = bsxfun(@times, H, W(:).');
      
    • Matrix multiplication:

      res = diag(W) * H;
      
    • A loop:

       res = nan(size(H));
       for k = 1:size(H,2)
           res(:, k)= W .* H(:, k);
       end