简体   繁体   中英

MATLAB: Improving for-loop

I need to multiply parts of a column vector with a fixed row vector. I solved this problem using a for-loop. However, I am wondering if the performance can be improved as I have to perform this kind of computation around 50 million times. Here's my code so far:

multMat = 1:5;
mat = randi(5,10,1);
windowSize = 5;

vout = nan(10,1);
for r = windowSize : 10
    vout(r) = multMat * mat( (r - windowSize + 1) : r);
end

I was thinking about uisng arrayfun . However, first I don't know how to adress the cell range (ie the previous five cells including the current cell), and second, I am not sure if arrayfun will be any faster than using the loop?

This sliding vector multiplication you're describing is an example of what is known as convolution . The following produces the same result as the loop in your example:

vout = [nan(windowSize-1,1);
        conv(mat,flip(multMat),'valid')];

If your output doesn't really need the leading NaN values which aren't overwritten in your loop then the conv expression is sufficient without concatenating the NaN elements to it.

For sufficiently large vectors this is of course not guaranteed to be as fast as you'd like it to be, but MATLAB's built-in convolution implementation is likely to be pretty close to an optimal tool for the job.

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