# Find Array Elements That Meet a Condition

I have an array of 5 numbers (say m). I want the following operation

m=[-1,-3,-2,-5,-4] For (j=1,j==5,j++) if m(j)-m(j+1)>0

Display the index and array element value of array m and exit the loop.

You can use SequencePosition to find the positions:

m = {-1, -3, -2, -5, -4};

positions = First /@ SequencePosition[m, {x_, y_} /; x > y]


{1, 3}

Then you can get corresponding values:

values = m[[pos]]


{-1, -2}

If necessary, you can combine both arrays into one:

Transpose[{pos, values}]


{{1, -1}, {3, -2}}

ClearAll[f]
f = Transpose@Pick[Most@Transpose[{#, Range@Length@#}], Sign@Differences@#, -1] &;

{values, positions} = f@{-1, -3, -2, -5, -4}


{{-1, -2}, {1, 3}}

Note: You could similarly modify the answers posted in your related question to get an answer to this question of yours.

Loops are not usually needed in Mathematica to solve problems. Functional Programming and Patterns can do job more efficiently

m = {-1, -3, -2, -5, -4};
{Flatten@#, Extract[m, #]}\[Transpose]&@Position[Reverse@Differences[Reverse@m],
_?(# > 0 &)]
(* Note: for a one-dimensional list provided it does not hurt to use Flatten *)

(* {{1, -1}, {3, -2}} *)


However, if you want to rely on procedural programming with use of loops you can use Do or For

Do[If[m[[i]] - m[[i + 1]] > 0, Print["index: ",i, " value: ",m[[i]]]], {i, Length@m - 1}]
(* index: 1 value: -1
index: 3 value: -2
*)

• Sir, please also suggest me how to store the result values in an array Jun 19, 2017 at 14:45