Reputation: 145
I have a vector, a very long vector composed of integers in MATLAB. My question is what is a fast efficient way to check to see if that vector is non-decreasing in MATLAB? The vector has a few thousand elements, all positive integers. The vector starts with some positive integer, repeats a few dozens times and then is supposed to increment by one and repeat. For example, the vector should look something like
a = [5 5 5 5 6 6 6 6 6 6 6 7 7 8 8 9 9 9 10 10 10 10 11];
The problem is that we suspect that the counter may have screwed up occasionally so once in a while the counter decreases and then increases, something like
b = [5 5 5 5 6 6 6 7 7 6 6 7 7 8 8 9 9 9 10 11 10 10 11];
so first I need to see if the sequence is non-decreasing. Then if it ever does decrease, it would be nice to know all the indices where the sequence decreases like that. I could only think of using first differences and checking to see if all entries are either zero or one. Any other clever ideas?
Thanks.
Upvotes: 1
Views: 763
Reputation: 516
To check whether the sequence is non-decreasing, you can use one of the following:
all(diff(b) >= 0)
~any(diff(b) < 0)
To find the specific positions where it decreases:
find(diff(b) < 0) + 1
Upvotes: 6
Reputation: 26069
use diff
and any
:
any(diff(b)<0)
this will return true (1) if the sequence is decreasing and false (0) for non-decreasing.
Upvotes: 5