Multiplication of two matrices of different rank

5 views (last 30 days)
I am curious that whether there is a clean way to do the multiplication of two matrices(tensor, strictly speaking) of different ranks?
For example, let say A=100*100*200, B=200*3. Therefore the product would be 100*100*3.
The built-in function 'A*B' seems to refuse to accept the parameters with different ranks, namely, it only accept A B with same rank(both 2-d matrix or both 3-d matrix). However, I can come up with a tentative way that is to reshape A(100*100*200) to another matrix (10000*200) and do the multiplication and reshape it back to (100*100*3) from the result (multiply((10000*200),(200*3))= 10000*3). But I am still curious about some clean or 'orthodoxical' way

Accepted Answer

Bruno Luong
Bruno Luong on 28 Sep 2018
Edited: Bruno Luong on 28 Sep 2018
RESHAPE is a cleanest and fastest way to do tensor-extension of mtimes on multi-dimension arrays.
szA = size(A);
szB = size(B);
n = szB(1);
if n ~= 1 || szA(end)==1
szA(end) = [];
end
szB(1) = [];
AB = reshape(A,[prod(szA),n])*reshape(B,[n,prod(szB)]);
AB = reshape(AB,[szA,szB]);
  2 Comments
Bruno Luong
Bruno Luong on 28 Sep 2018
Edited: Bruno Luong on 28 Sep 2018
Just edit to handle empty array(s), thanks Steph. ;-)

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 28 Sep 2018
Edited: Stephen23 on 28 Sep 2018
" I can come up with a tentative way that is to reshape ... and do the multiplication and reshape it back"
That seems like about the cleanest way using basic MATLAB commands. You could even stick that in its own function, something like this:
function D = tensortimes(A,B)
Sa = size(A);
Sb = size(B);
D = reshape(mtimes(reshape(A,[],Sa(end)),reshape(B,Sb(1),[])),[Sa(1:end-1),Sb(2:end)]);
end
Special cases will need to be handled as well.
  3 Comments
Stephen23
Stephen23 on 28 Sep 2018
@Bruno Luong: no doubt empty arrays will also need to be handled. I leave that as an exercise for the reader.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!