SergioABP
SergioABP

Reputation: 345

Dot product of matrix and vector without a loop

Suppose we have a Mx3 matrix and a 1x3 vector. How can I compute the dot product of each column and the vector without using a loop?

Upvotes: 0

Views: 465

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60680

Using Dev-iL’s example data:

M = rand(8,3);
V = 1:3;

the dot product of each row of M with V is simply the matrix product with a transposed V:

M * V'

Note that ' returns the conjugate transpose, which you need for the dot product.


Computing the dot product with the columns of M, as stated in the question, is nonsensical because the dimensions don’t match, hence I presume you meant rows (as the other answers did).

Upvotes: 2

Dev-iL
Dev-iL

Reputation: 24169

If I understood your question correctly,

M = rand(8,3); V = 1:3;
P = sum( M .* V, 2 ); % or in older MATLAB versions: sum( bsxfun(@times, M, V), 2 );

If you're dealing with complex numbers, you might have to conjugate one of the inputs.

Upvotes: 2

Related Questions