Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave/Matlab: Efficient calc of Frobenius inner product?

I have two matrices A and B and what I want to get is:

trace(A*B)

If I'm not mistaken this is called Frobenius inner product.

My concern here is about efficiency. I'm just afraid that this strait-forward approach will first do the whole multiplication (my matrices are thousands of rows/cols) and only then take the trace of the product, while the operation I really need is much simplier. Is there a function or a syntax to do this efficiently?

like image 945
lithuak Avatar asked Nov 07 '11 00:11

lithuak


2 Answers

Correct...summing the element-wise products will be quicker:

n = 1000

A = randn(n);
B = randn(n);

tic
sum(sum(A .* B));
toc

tic
sum(diag(A * B'));
toc
Elapsed time is 0.010015 seconds.
Elapsed time is 0.130514 seconds.
like image 92
John Colby Avatar answered Oct 16 '22 15:10

John Colby


sum(sum(A.*B)) avoids doing the full matrix multiplication

like image 35
stardt Avatar answered Oct 16 '22 17:10

stardt