Element wise multiplication of vectors within matrices when multiplying matrices.

7 views (last 30 days)
Hi there, I wonder if you can help!....
I would like to multiply multiple 4x4 matrices together but each element of each matrix is a variable, and so in MATLAB is a vector. I therefore want to perform matrix multiplication on the matrices but element by element multiplication of the vectors inside, is this possible?
e.g when multiplying M1*M2 where M1=[A B ; C D], M2=[E F; G H] and A-H are all vectors
I want MATLAB to return [A.*E+B.*G A.*F+B.*H ; C.*E+D.*G C.*F+D.*H]
I can type out the formula for 2 matrices easily, but 10 matrices? It gets long very quickly! Can this be done quickly?
Many thanks, Luke

Answers (1)

AJ von Alt
AJ von Alt on 17 Jan 2014
One way to perform the desired operation is to use a for loop to iterate through the third dimension of M1 and M2 and perform 2-D matrix multiplication at each level.
k = size( M1 , 3 ); %the size of the third dimension
for i = 1:k % for each level of the 3-D matrix
OUT(:,:,i) = M1(:,:,i) * M2(:,:,i); % multiply the corresponding 2D matrices
end
Assuming your vectors are all of length k with M1 of size ( m X n X k ) and M2 size ( n X p X k ), the result of this operation OUT will be size ( m X p X k ).
Below is a complete demonstration of this operation.
%%Inputs
m = 2;
n = 3;
p = 4;
M1(:,:,1) = 1 * ones( m , n );
M1(:,:,2) = 2 * ones( m , n );
M1(:,:,3) = 3 * ones( m , n );
M2(:,:,1) = 1 * ones( n , p );
M2(:,:,2) = 2 * ones( n , p );
M2(:,:,3) = 3 * ones( n , p );
%%Perform 2-D matrix multiplication at each level of the 3-D matrix
k = size( M1 , 3 ); %the size of the third dimension
OUT = zeros( m , p , k ); % preallocate OUT
for i = 1:k % for each level of the 3-D matrix
OUT(:,:,i) = M1(:,:,i) * M2(:,:,i); %multiply the corresponding 2D matrices
end

Community Treasure Hunt

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

Start Hunting!