# Matlab Matrix multiplication element wise from different sized matrices

I am optimizing a MatLab script by using vector multiplication instead of for loops. There, I got a problem with the vector selection.

In my calculation I got two matrices, M1(x,x,x,x) and M2(x,x). When I try to vectorize those matrices and multiplicate them elementwise, I get an error. Their sizes mismatch.

product = M1(1,1,:,1) .* M2(:,1) size(M1(1,1,:,1) -> 1 1 6 size(M2(:,1)) -> 6 1

If I use the command squeeze on M1 it is working.

product = squeeze(M1(1,1,:,1)) .* M2(:,1)

The problem is, squeeze takes extremely much time (1/5 of the complete time -> ~50s). How can I still use my matrices without using squeeze? Anyone got an Idea?

Thanks for your help!

## Answers

shiftdim is usually faster, so try

product = shiftdim(M1(1,1,:,1),2) .* M2(:,1)