1
$\begingroup$

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.

$\endgroup$
0

3 Answers 3

3
$\begingroup$

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}}

$\endgroup$
1
$\begingroup$
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.

$\endgroup$
0
$\begingroup$

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
*)
$\endgroup$
1
  • $\begingroup$ Sir, please also suggest me how to store the result values in an array $\endgroup$ Jun 19, 2017 at 14:45

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.