Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code this matrix multiplication?

I have two matrices:

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

B = A'

The multiplication should take in the way as if row and column vector is extracted from both.
C = B(:,i) * A(i,:) such that for first instance (1st row and 1st column) the result would be:

[1 2; 
 2 4]

This will be summed up vertically to obtain [3 6]. This sum will give final answer 9. Likewise, 2nd row & 2nd column, 3rd row & 3rd column and so on if matrix size is higher.

This final scalar value will be used for comparing which row and its corresponding column has high yield.

like image 280
user9003011 Avatar asked Nov 24 '17 10:11

user9003011


2 Answers

Your required result is actually mathematically equivalent of:

sum(A,2).^2   %or  sum(A,2) .* sum(A,2) 

If A and B are not transpose of each other then:

sum(A,2).* sum(B,1).' 
like image 159
Sardar Usama Avatar answered Oct 01 '22 00:10

Sardar Usama


You can use sum:

result = sum(bsxfun(@times,sum(A,2), B.'),2);

Or in the recent version of MATLAB you can write:

result = sum(sum(A,2).*B.',2)

Previous answer:

You can use permute:

result = sum(reshape(permute(A,[2 3 1]) .* permute(A,[3 2 1]),[],size(A,1)));

Or in the case of A and B:

result = sum(reshape(permute(B,[1 3 2]) .* permute(A,[3 2 1]),[],size(A,1)));

result = [9 49 121]

Thanks to @TommasoBelluzzo and @SardarUsama .

like image 22
rahnema1 Avatar answered Oct 01 '22 02:10

rahnema1