Logical indexing without for loop
5 ビュー (過去 30 日間)
This is probably a simple question, but I would love some input from those who can lend it. I have a vector [A] I would like to index according to a condition comparing the nth entry of A with the one following it (n+1).
For instance, if A is [1,2,3,4,5,6,7,6,5,4,3,2,1], and I would like to know which entries of A are larger than the entry preceding it, I would try to do the following:
for i = 1:size(A)
if i > 1
j = A(i) > A(i-1);
Where j = [0,1,1,1,1,1,1,0,0,0,0,0,0]
Is there a way to do this without using a loop? Any help would be appreciated, thank you.
その他の回答 (1 件)
Walter Roberson 2016 年 4 月 19 日
[abs(diff(A)) > 0.001, false]
The false compensates for the fact that diff(A) is one shorter than A itself. You will find that in practice it is not a problem to use a logical index shorter than the array dimension, so for most purposes
abs(diff(A)) > 0.001
would be just as good.