How to check monotonity of a vector?

140 次查看(过去 30 天)
How to check easily that components of a vector form a monotone (increasing) sequence or not?
  1 个评论
Adam
Adam 2017-12-15
You can use
validateattributes( yourVector, { 'numeric' }, { 'vector', 'increasing' } )
if you just want to validate that it is monotonic and carry on with the code if it is while throwing an error otherwise.

请先登录,再进行评论。

采纳的回答

KL
KL 2017-12-15
编辑:KL 2017-12-15
use diff
along with all maybe
a = 1:10;
isIncreasing = all(diff(a)) %or all(diff(a)>=0) if you want to allow 0 difference
  1 个评论
Andreas
Andreas 2022-3-16
Take care, that all is also true for negative values.
Therefore, this example has a false positive on b
a = [1:10];
b = [1 2 3 2 1 5];
isIncreasingA = all(diff(a))
isIncreasingA = logical
1
isIncreasingB = all(diff(b))
isIncreasingB = logical
1
To fix that, restrict to positive values of diff
isIncreasingA = all(diff(a)>0)
isIncreasingA = logical
1
isIncreasingb = all(diff(b)>0)
isIncreasingb = logical
0

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2017-12-15
issorted() with 'ascend' (repeats permitted) or 'strictascend' (repeats not permitted)

类别

Help CenterFile Exchange 中查找有关 Files and Folders 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by