How to find the first element in ascending numbers that repeat?

3 views (last 30 days)
I want to find the index of the first instance of a number only when the next number is ascending.
A = [1 2 3 4 0 1 0 1 0 1 0 1 2 3 4 0 1 0 1 0 1 1 2 3 4]
b = find(A==1)
Actual Output:
1 6 8 10 12 17 19 21 22
Desired Output:
1 12 22

Accepted Answer

DGM
DGM on 8 Apr 2021
Edited: DGM on 8 Apr 2021
You said you want the first instance where the next number is larger, but the desired output you gave [1 12 22] is all instances where the next number is larger.
A = [0 5 1 0 1 2 3 4 0 1 0 1 0 1 0 1 2 3 4 0 1 0 1 0 1 1 2 3 4]
numtofind = 1;
% find all instances
% ignore the last element, since it has no following element
b = find(A(1:end-1)==numtofind)
% pick whichever type of result you need
%b = b(find(A(b)<A(b+1),1)) % the first instance where the next number is larger
b = b(A(b)<A(b+1)) % all instances where the next number is larger
Just pick whichever one you need.
  2 Comments
Mirthand
Mirthand on 8 Apr 2021
Thank you! I needed (% all instances where the next number is larger).
Is there a way to change it from the next number is larger to the next two numbers are larger?
For example if I wanted to use numtofind = 0;
I want to ignore 010101
but keep instances where 012
DGM
DGM on 8 Apr 2021
Sure
A = [0 5 1 0 1 2 3 4 0 1 0 1 2 1 0 1 2 3 4 0 1 0 1 0 1 1 2 3 4 1]
numtofind = 1;
b = find(A(1:end-2)==numtofind) % find all instances
b = b(A(b)<A(b+1) & A(b)<A(b+2)) % all instances where the next two numbers are larger

Sign in to comment.

More Answers (1)

Bruno Luong
Bruno Luong on 8 Apr 2021
A = [1 2 3 4 0 1 0 1 0 1 0 1 2 3 4 0 1 0 1 0 1 1 2 3 4]
b = find(A(1:end-1)==1 & diff(A)>0)

Tags

Community Treasure Hunt

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

Start Hunting!