-1

What's the best way to do the following (in Matlab) if I have two matrices A and B, let'say both of size m-by-n:

C = zeros(m,m);
for t=1:n
    C=C+A(:,t)*B(:,t)';
end
horchler
  • 18,384
  • 4
  • 37
  • 73
  • 1
    Am I missing something or is this really plain matrix multiplication i.e. `C = A * B;`? – Notlikethat Jan 12 '14 at 19:30
  • By the way, since you mentioned efficiency, Matlab is crazy-good with matrix multiplication, check out [this post](http://stackoverflow.com/questions/6058139/why-is-matlab-so-fast-in-matrix-multiplication) for discussion. – Bruce Dean Jan 12 '14 at 19:39

1 Answers1

1

This is nothing more than

C = A*B';

where A and B are each m-by-n. I'm not sure that you're going to get more efficient than that unless the matrices have special properties.

One place where you might get a benefit from using bsxfun for matrix multiplication is when the dimensions are sufficiently large (probably 100-by-100 or more) and one matrix is diagonal, e.g.:

A = rand(1e2);
B = diag(rand(1,1e2));
C = bsxfun(@times,A,diag(B).');

This occurs in many matrix transforms – see the code for sqrtm for example (edit sqrtm).

horchler
  • 18,384
  • 4
  • 37
  • 73
  • @LuisMendo: I assume that you're referring to `A*B'`. The complex conjugate transpose is used because both `A` and `B` are `m`-by-`n` where `m` might not be equal to `n`. This is also consistent with the code specified by the OP. Note that `transpose` (`.'`) is used in the second case as we are just rearranging elements. – horchler Jan 13 '14 at 01:08
  • @horchler Sorry, I got confused. I thought you were applying `'` to `B` when only `.'` was required; but now I see that the OP uses `'` – Luis Mendo Jan 13 '14 at 11:16