2
$\begingroup$

Suppose I have the code

Do[If[f[i,j]==1,{output[i]=j,Break},Continue],{i,1,5},{j,1,1000}] 

Where $f$ is just a function.

I want the code to find the first $j$ that works for $i$, then Break and then find the first $j$ that works for the next $i$, until a $j$ has been found for each $i$.

Instead what is happening is the code seems to go through all the $j$’s for each $i$ and then it remembers the last $j$ that works as output[i].

$\endgroup$

2 Answers 2

8
$\begingroup$

First of all, the correct commands are Break[] and Continue[], you are missing the square brackets.

Secondly, you do not need Continue[].

Thirdly, use ; instead of , to join two expressions.

Lastly, Break[] exits the nearest enclosing Do, so use two separate Do statements:

Do[Do[If[f[i, j] == 1, output[i] = j; Break[]], {j, 1, 1000}], {i, 1, 5}]
$\endgroup$
7
$\begingroup$

More Mathematica-like would be on-demand calculation and memoization:

Clear[output];
output[i_] := output[i] = SelectFirst[Range[1000], f[i, #] == 1 &]

Alternatively, you can try

Clear[output];
output[i_] := output[i] =
  j /. FindInstance[f[i, j] == 1, j, PositiveIntegers, 1][[1]]

which may use better tools than simply iterating over $j$.

$\endgroup$

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.