How to multiply each row of a matrix by corresponding column of another matrix in matlab?

StackOverflow https://stackoverflow.com/questions/21900514

  •  14-10-2022
  •  | 
  •  

Question

I have two matrices A and B. A is N-by-L matrix and B is L-by-N matrix.

A = [1 2 3;
     4 5 6];

B = [ 7   8;
      9  10;
     11  12];

I would like to multiply the each row of the first matrix by the corresponding column of the second matrix. After the multiplication I would have a (Nx1) vector. The result would be

C = [ 1*7 + 2*9  + 3*11,
      4*8 + 5*10 + 6*12];

I can perform the multiplication with a for loop, but it is not efficient for large matrices.

ASize = size(A);
for i = 1:ASize(1),
    C(i) = A(i,:) * B(:,i);
end

Is there a better way to do this?

Était-ce utile?

La solution

I think this should do the trick:

 C = sum(A.*B', 2);   

Autres conseils

I think this will work better and is simple

C=diag(A*B);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top