简体   繁体   English

MATLAB:改进for循环

[英]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. 我使用for循环解决了这个问题。 However, I am wondering if the performance can be improved as I have to perform this kind of computation around 50 million times. 但是,我想知道性能是否可以提高,因为我必须执行大约5000万次这种计算。 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 . 我在想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? 但是,首先我不知道如何处理单元格范围(即包括当前单元格的前五个单元格),其次,我不确定arrayfun是否会比使用循环更快?

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. 如果您的输出实际上不需要在循环中未被覆盖的前导NaN值,那么conv表达式就足够了,而不会将NaN元素连接到它。

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. 对于足够大的向量,这当然不能保证你想要的那么快,但是MATLAB的内置卷积实现可能非常接近于工作的最佳工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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