Reputation: 35
I am trying to vectorize this for loop. Any idea?
D = 1x8851;
for k = 1:length(D)-1
P(k) = ((D(k)<=0)&&(D(k+1)>=0))||((D(k)>=0)&&(D(k+1))<0);
end
Upvotes: 0
Views: 43
Reputation: 60504
For two things having different signs, it means that their product is negative:
P(k) = ((D(k)<=0)&&(D(k+1)>=0))||((D(k)>=0)&&(D(k+1))<0);
is the same as:
P(k) = ( D(k) * D(k+1) ) <= 0;
This is simple to vectorize by simply converting operations to element-wise operations:
P = ( D(1:end-1) .* D(2:end) ) <= 0;
The original construct can be vectorized in the same way, with &
and |
being the element-wise counterparts to &&
and ||
:
P = ((D(1:end-1)<=0)&(D(2:end)>=0))|((D(1:end-1)>=0)&(D(2:end))<0);
However, the shorter expression requires fewer intermediate matrices and fewer operations, and therefore will be faster.
Upvotes: 3