如何对此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)
预期结果是:
win =
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
vec =
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0
答案 0 :(得分:4)
使用bsxfun
-
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]))
请注意,对于预分配,您还可以使用此faster scheme
-
win(size(data,1),2*shift+1) = 0;