# Thread: Multiplying layers of a 3D matrix

1. ## Multiplying layers of a 3D matrix

I am attempting to multiply each layer of a 2x2x4 matrix together. i.e. the first layer will be (:,:,1)...therefore Z(:,:,1)=X(:,:,1)*Y(:,:,1)...and so on until i reach the fourth layer.
The for loop is a simple way of visualising this problem, but Im trying to speed up the code by vectorising and im at a loss as to how to go about this.
Could someone be as kind as to point me in the right direction? Any further questions/ discussion are very welcome.

X = rand(2,2,4)
Y = rand(2,2,4)
Z = zeros(2,2,4)

for i = 1 : 4
Z(:,:,i) = X(:,:,i)*Y(:,:,i)
end

2. ## Re: Multiplying layers of a 3D matrix

Originally Posted by p123nky
I am attempting to multiply each layer of a 2x2x4 matrix together. i.e. the first layer will be (:,:,1)...therefore Z(:,:,1)=X(:,:,1)*Y(:,:,1)...and so on until i reach the fourth layer.
The for loop is a simple way of visualising this problem, but Im trying to speed up the code by vectorising and im at a loss as to how to go about this.
Could someone be as kind as to point me in the right direction? Any further questions/ discussion are very welcome.

I could be wrong, but I don't think you are going to significantly improve on that, but you could try asking on a specialised Matlab forum such as: Newsreader - MATLAB Central