0

Say I have an array A = [ 1 3 4 6 7 8] and another array of the same size S = [1 1 0 1 0 1].

I need to check if A(i)+S(i) is greater than or equal to A(i-1)+S(i-1), for the entire length of the array. In other words I'm checking if A + S is monotonically increasing.

However, if S(i-1) is zero, then I want to compare A(i)+S(i) to A(i-2)+S(i-2) instead.

Simply speaking, I need to check if all the elements in A+S are monotonically increasing, ignoring the ones with S=0.

Viktor
  • 3,436
  • 1
  • 33
  • 42
Shock-o-lot
  • 135
  • 1
  • 1
  • 11
  • ok.....so what is the question? – ale64bit Jun 17 '16 at 22:08
  • 3
    As soon as [`diff`](http://mathworks.com/help/matlab/ref/diff.html) goes negative it's no longer increasing. Use [logical indexing](http://stackoverflow.com/questions/32379805/linear-indexing-logical-indexing-and-all-that) to remove the `S=0` elements. – Adriaan Jun 17 '16 at 22:15

1 Answers1

1

Try this

isequal(sort(A(S)),A(S)) % or isequal(sort(A(S==1)),A(S==1)) 

Or if S is not a logical matrix, i.e. can have values other than 1 and 0

idx = S ~= 0;
isequal(sort(A(idx)),A(idx))

Adriaan's suggestion should be faster, especially on large matrices

all(diff(A(S~=0)) >= 0) % or replace >= with > if you want it to be strictly increasing
Dan
  • 45,079
  • 17
  • 88
  • 157