I have X as a 616 x 1 double. I calculated the differences between adjacent elements of X by using:


and get Y as a 615 x 1 double, containing positive and negative numbers, including 0 (zero).

If I'm using


I'll get the answer as 615 x 1 logical, which is not the answer I'm expecting.

My questions are

  • how can I extract only the element of X which the difference is 0?
  • how can I detect where the decrease and increase trends starts?

1 Answer 1


If you are trying to find the entries with numerical difference being zero, you might end up with nothing because the differences may be non-zero for all entries because they are double, and assuming these 616 entries are approximation to something.

I suggest you might wanna try to set a tolerance Tol: for example

 X = sin(linspace(0,2*pi,616)'); 
 % this gives you an X being the grid approximation to sine
 Y = diff(X);
 Tol = 1e-2*2*pi/615;
 indY = find(abs(Y) < Tol);
 % the index of the difference vector that has absolute value < Tolerance

Then X(indY) and X(indY+1) will give you the entries of X that produces these less-than-tolerance differences. If the latter is bigger than the former, then X starts to increase (approximation), vice versa.

MATLAB gives:

  >> X(indY)
     ans =
  >> X(indY+1)
     ans =

The criteria for choosing Tol is more like an a priori guess. First you have the length of the interval I set being $2\pi$, there is $616$ grid points, which has a magnitude of 1e2. The true derivative of $\sin x$ is $\cos x$, which has absolute value less than $1$, so the all the numerical differences should be less than or equal to $h = 2\pi/615$. Now I already know sine, when near its extrema, increases or decreases like a linear function (imagine Taylor expansion, or small angle approximation), and it takes about 100 grids to make it the maximum (knowing a priori for sine). Therefore the absolute value of the difference being less than the magnitude of the 1e-2 times the grid size would suffice to say that, X almost remains the same. It is problem dependent.

  • $\begingroup$ may i know how do decide the value of tolerance? $\endgroup$
    – newbee
    Jul 26, 2013 at 3:24
  • $\begingroup$ @newbee Please see my edits. $\endgroup$
    – Shuhao Cao
    Jul 26, 2013 at 3:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.