Clear Filters
Clear Filters

How can we compute batch matrix-matrix product of matrices (3-D tensors) in MATLAB?

9 views (last 30 days)
I have two 3-D tensors of size b*n*m and b*m*p. I need the product of these two tensors to get the output size as b*n*p. I have used direct matrix multiplication using * operator. Moreover, I have used 'pagetimes'. But it is not working. Is there any function in MATLAB like 'torch.bmm' in python as shown in link: https://pytorch.org/docs/stable/generated/torch.bmm.html to do the matrix multiplication of two 3-D tensors.

Accepted Answer

Bruno Luong
Bruno Luong on 5 Dec 2023
b = 2;
n = 3;
m = 4;
p = 5;
A = rand(b,n,m);
B = rand(b, m,p);
AA = permute(A, [2 3 1]);
BB = permute(B, [2 4 1 3]);
AB=pagemtimes(AA, BB);
AB=permute(AB,[3 1 4 2]);
size(AB)
ans = 1×3
2 3 5
AB
AB =
AB(:,:,1) = 1.1069 0.9331 1.2839 0.4248 1.0635 1.2576 AB(:,:,2) = 1.3688 1.5129 1.6656 0.6568 1.2286 1.3592 AB(:,:,3) = 1.0351 1.2450 1.3362 0.4743 1.1831 1.3162 AB(:,:,4) = 1.2485 1.0840 1.4573 0.7987 1.7168 1.7815 AB(:,:,5) = 0.5739 0.7361 0.7294 0.9621 1.9460 2.0458
  5 Comments
BIPIN SAMUEL
BIPIN SAMUEL on 7 Dec 2023
I refer to the deep learning layer where input is 3-D tensor in the formatted dlarray and I want to do these operations as a part of forming that layer.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!