Reputation: 10790
QUESTION
I'm looking for an elegant way to multiply two arrays along one particular dimension.
SIMILAR QUESTION
There is already a similar question on the official matlab forum, but the thread is outdated (2004).
EXAMPLE
M1
a [6x4x4] matrix and M2
a [6x1] matrix, I would like to multiply (element by element) M1
with M2
along the 3rd dimension of M1 to obtain a matrix M [6x4x4]
An equivalent to:
M1 = rand(6,4,4);
M2 = rand(6,1);
for ii = 1:size(M1,2)
for jj = 1:size(M1,3)
M(:,ii,jj) = M1(:,ii,jj).*M2;
end
end
VISUAL EXAMPLE
Do you know a cool way to do that ? (no loop, 1 or 2 lines solution,...)
Upvotes: 1
Views: 705
Reputation: 104555
If I'm interpreting your question correctly, you want to take each temporal slice (i.e. 1 x 1 x n
) at each spatial location in M1
and element-wise multiply it with a vector M2
of size n x 1
. bsxfun
and permute
are perfect for that situation:
M = bsxfun(@times, M1, permute(M2, [2 3 1]));
Upvotes: 4