How to multiply higher order matrices?
35 次查看(过去 30 天)
显示 更早的评论
Hello, I am attempting to multiply a 5D 3x3x3x3x3 matrix and a 5D 3x3x3x3x1 matrix in order to produce a 4D matrix of 3x3x3x3 after squeeze operation is applied.
Here's is what it would look like in an equation.
Multiplying a 3x3 by a 3x1 works no problem,
A = ones(3,1);
B = ones(3,3);
C = B*A;
However when I try to extend this to higher orders, I recieve and error
A = ones(3,3,3,3,1);
B = ones(3,3,3,3,3);
C = B*A;
The error suggests I use pagemtimes, but I'm not so sure those are the correct operations for my application. How would I go about coding this correctly?
EDIT: I believe I might have found the right answer, but not sure. The code below leads me to believe this might be correct
A = ones(3,1,3);
B = ones(3,3,3);
C = pagemtimes(B,A);
which would then exent to
A = ones(3,1,3,3,3);
B = ones(3,3,3,3,3);
C = pagemtimes(B,A);
EDIT2: Yes the above works, you can check it will the code below
clear all
a = 10;
%% Convert 3D matrix to 5D for tensor matrix multiplication
Bx = 1*ones(a,a,a);
By = 2*ones(a,a,a);
Bz = 3*ones(a,a,a);
B(1,1,:,:,:) = Bx;
B(2,1,:,:,:) = By;
B(3,1,:,:,:) = Bz;
%% Generate 5D tensor matrix
exx = 1*ones(a,a,a);
exy = 2*ones(a,a,a);
exz = 3*ones(a,a,a);
eyx = 4*ones(a,a,a);
eyy = 5*ones(a,a,a);
eyz = 6*ones(a,a,a);
ezx = 7*ones(a,a,a);
ezy = 8*ones(a,a,a);
ezz = 9*ones(a,a,a);
eT(1,1,:,:,:) = exx;
eT(1,2,:,:,:) = exy;
eT(1,3,:,:,:) = exz;
eT(2,1,:,:,:) = eyx;
eT(2,2,:,:,:) = eyy;
eT(2,3,:,:,:) = eyz;
eT(3,1,:,:,:) = ezx;
eT(3,2,:,:,:) = ezy;
eT(3,3,:,:,:) = ezz;
%% Multiply 3x3 3D matrix by 3x1 3D matrix
A = pagemtimes(eT,B);
%% Convert 5D matrix into 3 3D matrix components
Ax = squeeze(A(1,1,:,:,:));
Ay = squeeze(A(2,1,:,:,:));
Az = squeeze(A(3,1,:,:,:));
%% Ax should = 14 at each location
%% Ay should = 32 at each location
%% Az should = 50 at each location
2 个评论
Torsten
2021-5-25
Is there any standard definition for the multiplication of matrices of dimension greater than 2 ?
I think no. So you will have to program the operation on your own.
采纳的回答
更多回答(2 个)
James Tursa
2021-5-25
You may need to permute your arrays first to get your desired 2D slices in the first two dimensions.
A = whatever
B = whatever
Ap = permute(A,[4 5 1 2 3]);
Bp = permute(B,[4 5 1 2 3]);
Then use pagemtimes
C = pagemtimes(Bp,Ap);
Then if needed you can permute the answer back
C = permute(C,[3 4 5 1 2]);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!