Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
nawara Avatar asked Dec 05 '25 07:12

nawara


1 Answers

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
    
like image 58
bdecaf Avatar answered Dec 07 '25 16:12

bdecaf