Reputation: 459
I'm wondering if it is possible to perform a multidimensional matrix multiplication without resorting to a for-loop. Given the N-by-P matrix A and the N-by-M-by-P matrix B, I want to compute the M-dimensional vector y, defined element-wise as
y(j) = sum_(i = 1,...,N) sum_(k = 1,...,P) A(i,k)*B(i,j,k)
Upvotes: 2
Views: 464
Reputation: 112679
You can linearize A
into a row vector, then reshape
and permute
the array B
as a matrix, so that the desired result is just matrix multiplication:
M = 5;
N = 6;
P = 8;
A = rand(N,P);
B = rand(N,M,P);
result = A(:).'*reshape(permute(B, [1 3 2]), [], M);
Or reshape
matrix A
so that its dimensions are aligned with those of B
, use bsxfun
to multiply with singleton-expansion, and sum over the two desired dimensions:
result = sum(sum(bsxfun(@times, reshape(A, N, 1, P), B), 1), 3);
Upvotes: 3