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)

Need Your Help

Vectorizing Matlab replace array values from start to end

arrays matlab vectorization indices

I have an array in which I want to replace values at a known set of indices with the value immediately preceding it. As an example, my array might be

Fedora + Apache + Phusion passenger + Rails shows default apache page (always)

ruby-on-rails apache passenger fedora phusion

Even though there is a huge amount of information about this subject I'm still stuck at the apache default page shown by the server. The worse part is that everything seems to work properly.