Is it possible to multiply a 3D matrix with a coumn vector?

157 views (last 30 days)
Vipin Padinjarath on 31 Mar 2017
Commented: Roman Gorlov on 28 Jan 2021
I have a 3D matrix with three rows and three columns. I want to multiply this matrix with a column vector of 3 rows. How can it be done?

Jan on 31 Mar 2017
Edited: Jan on 31 Mar 2017
With Matlab >= 2016b:
A = rand(3, 3, 1000);
b = rand(3, 1);
C = squeeze(sum(A .* reshape(b, 1, 3), 2));
With older versions:
C = squeeze(sum(bsxfun(@times, A, reshape(b, 1, 3)), 2))
Richard on 19 Feb 2020
A = rand(3, 3, 1e6);
B = rand(3, 1);
tic, C = zeros(3, size(A, 3));
for i = 1:size(A, 3)
C(:,i) = A(:,:,i)*B ;
end, toc
tic; C = reshape(reshape(permute(A,[2,1,3]),3,[]).'*B,3,[]); toc
tic; C = squeeze(sum(bsxfun(@times, A, reshape(B, 1, 3)), 2)); toc
Elapsed time is 0.891301 seconds. % Loop
Elapsed time is 0.082350 seconds. % permute
Elapsed time is 0.088938 seconds. % sum(times())
Matlab 2019b Update 3

Andrei Bobrov on 31 Mar 2017
C = reshape(reshape(permute(A,[2,1,3]),3,[]).'*B,3,[]);
Jan on 31 Mar 2017
+1: This is the fastest solution.

KSSV on 31 Mar 2017
A = rand(3,3,3) ;
B = rand(3,1) ;
C = zeros(3,3) ;
for i = 1:3
C(:,i) = A(:,:,i)*B ;
end
Jan on 31 Mar 2017
+1: Clean and clear.

Tyler R on 26 May 2017
Edited: Tyler R on 26 May 2017
I got confused because some of the dimensions are size 3, but there is also a 3rd dimension, so for generalization's sake:
N = 150;
K = 20;
T = 30;
A = rand(N,K,T);
B = rand(K,1);
C = zeros(N,T);
Andrei's method:
C = reshape(reshape(permute(A,[2 1 3]),K,[]).'*B,N,[]);
Jan's method:
C = squeeze(sum(A .* reshape(B, 1, K), 2));
KSSV's method:
for t = 1:T
C(:,t) = A(:,:,t)*B ;
end
Roman Gorlov on 28 Jan 2021
When B is rand(K, P), with P > 1, then both proposed methods don't work. I've tried different permuations, but no luck replicating the for loop result.