Logical indexing without for loop

조회 수: 6 (최근 30일)
Tyler
Tyler 2016년 4월 19일
댓글: Tyler 2016년 4월 19일
Hi all,
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);
end
end
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.

채택된 답변

Renato Agurto
Renato Agurto 2016년 4월 19일
j = [0 A(2:end) > A(1:end-1)]
  댓글 수: 2
Tyler
Tyler 2016년 4월 19일
Awesome, thank you so much! If I wanted to do something more complicated, such as wanting the absolute value of the difference of the two entries to be greater than a certain value, could I do that?
Aa = [0 abs(A(1:end)-A(1:end-1)) > .001]
This doesn't quite work, but I might be forgetting something obvious.
Walter Roberson
Walter Roberson 2016년 4월 19일
You used A(1:end)-A(1:end-1) which subtracts two vectors of different sizes. Renato used A(2:end) for the first operation.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
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.
  댓글 수: 1
Tyler
Tyler 2016년 4월 19일
Thank you for your help!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by