Matlab 两个for循环的矢量化(矩阵创建和阈值化)

Matlab 两个for循环的矢量化(矩阵创建和阈值化),matlab,vectorization,Matlab,Vectorization,如何将此MATLAB函数矢量化: function [win,vec] = createwin(data,shift,regions,threshold) % % data ... 1D data array % shift ... positive integer scalar % regions ... integer index vector % threshold ... integer scalar % win = zeros(length(data),2*s

如何将此MATLAB函数矢量化:

function [win,vec] = createwin(data,shift,regions,threshold)
% 
% data      ... 1D data array
% shift     ... positive integer scalar
% regions   ... integer index vector 
% threshold ... integer scalar
%
win = zeros(length(data),2*shift+1);
for i = 1+shift:length(data)-shift
   win(i,:) = data(i-shift:i+shift);
end

vec = false(size(data));
for i = 1:length(regions)
    ii = max(1+shift, regions(i)-shift):min(length(data)-shift, regions(i)+shift);
    vec(ii) = data(ii) >= threshold & data(ii) >= win(ii);
end
我只是添加了第二个for循环,这是代码中的瓶颈。 那么,知道如何对第二个循环进行矢量化吗

还有一些测试用例:

[win,vec]=createwin(1:20,3,[2:18],10)
预期结果是:

赢=

vec=

一种方法-

请注意,对于预分配,您也可以使用此-


数据是矩阵还是向量?为了澄清,请发布一个带有输入(
data
shift
)和输出(
win
)的小示例。如果您发布了示例输入和输出,那就更好了。那么验证解决方案就更容易了。还有一些数据和shift的示例值,然后显示输出win?这不是我运行代码时得到的
win
。当
length(data)=8
时,您的
win
怎么会有10行?这个问题现在比第一个版本更完整了。它现在应该得到一次投票…好的。。。很好的解决方案,速度提高了20倍:)感谢Yair关于pre-allocation@Divakar的文章,这非常有用!
 0     0     0     0     0     0     0
 0     0     0     0     0     0     0
 0     0     0     0     0     0     0
 1     2     3     4     5     6     7
 2     3     4     5     6     7     8
 3     4     5     6     7     8     9
 4     5     6     7     8     9    10
 5     6     7     8     9    10    11
 6     7     8     9    10    11    12
 7     8     9    10    11    12    13
 8     9    10    11    12    13    14
 9    10    11    12    13    14    15
10    11    12    13    14    15    16
11    12    13    14    15    16    17
12    13    14    15    16    17    18
13    14    15    16    17    18    19
14    15    16    17    18    19    20
 0     0     0     0     0     0     0
 0     0     0     0     0     0     0
 0     0     0     0     0     0     0
 0     0     0     0     0     0     0     0     0     1     1     1     1     1     1     1     1     0     0     0
win = zeros(size(data,1),2*shift+1)
row_id = 1+shift:size(data,1)-shift
win(row_id,:) = data(bsxfun(@plus,row_id(:),[-shift:shift]))
win(size(data,1),2*shift+1) = 0;