简体   繁体   中英

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!

shiftdim通常更快,因此请尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM