开发者

Vectorization of logical expressions

I have a 1 x n array. I would like to check whether each element is greater than its five consequent elements. That is, i>i+1 & i>i+2 & i>i+3 & i>i+4 & i>i+5.

How would I do this开发者_运维百科 without any loops?


idx = 1:numel(x)-5;
I = x(idx) > x(idx+1) & x(idx) > x(idx+2) & x(idx) > x(idx+3) & x(idx) > x(idx+4) & x(idx) > x(idx+5)

Note that this doesn't really handle the last 5 elements of x because it depends on what you want the output to be.


Consider this vectorized solution:

N = 5;                                        %# number of consequent values
idx = hankel(2:N+1, N+1:numel(x));            %# indices of sliding windows
y = all( bsxfun(@gt, x(1:end-N), x(idx)) )    %# comparison

The result is a boolean vector, where y(i) indicates whether x(i) is greater than all of x(i+1), x(i+2), ..., x(i+N)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜