MATLAB: Fast multiplication of rows of one matrix and columns of the second matrix

matrixmatrix ma

I would like to compute v(k) = A(k, :)* B(:, k) as fast as possible (no-loops). Currently, I am doing diag(A * B) but it has unnecessary overhead of computation, and storage.

Best Answer

The fastest way to do something generally depends on the size and structure of your data.
Don't assume loops are slower. For simple linear algebra, loops are generally very fast. In fact for large matrices (1000x1000 etc.), I think loops are probably the fastest way actually.
v = zeros(1,size(A,1));
for k = 1:size(A,1)
v(k) = A(k,:)*B(:,k);
end
For smaller matrices, you are probably better off doing this:
v = sum(A'.*B);
The best thing to do it just to try things out and see what works best for your data.