5
$\begingroup$

I have a Do loop with several conditions:

Do[If[i < 20, a[i] = i; If[i == 19, a[i] = i + 1], a[i] = i + 3], {i,1, 100}]

How can I rewrite the If condition in the Do loop? Is there any better way to show that?

$\endgroup$

5 Answers 5

13
$\begingroup$

With Piecewise you can write it in classical mathematical form:

a[i_] = Piecewise[{{i, i <= 18}, {i + 1, i == 19}}, i + 3]

$$ \begin{cases} i & i\le18 \\ i+1 & i=19 \\ i+3 & \text{True} \end{cases} $$

Array[a, 100]
(*    {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 20, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
       38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
       55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
       72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
       89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103}    *)

Going further, PiecewiseExpand can be very helpful in combining and simplifying such expressions.

$\endgroup$
9
$\begingroup$

Here's an alternative approach. Instead of a loop

Do[If[i < 20, a[i] = i; If[i == 19, a[i] = i + 1], a[i] = i + 3], {i, 1, 100}]

use pattern matching

aa[i_ /; i == 19] = i + 1;
aa[i_ /; i < 20] = i;
aa[i_ /; i <= 100] = i + 3;

And @@ Table[a[j] == aa[j], {j, 1, 100}]
(* True *)
$\endgroup$
7
$\begingroup$

Sometimes using Which is easier to understand compared to nested If.

Do[
 Which[
  i == 19, aa[i] = i + 1,
  i < 20, aa[i] = i,
  True, aa[i] = i + 3],
 {i, 1, 100}]

And @@ Table[a[j] == aa[j], {j, 1, 100}]
(* True *)
$\endgroup$
4
$\begingroup$
a=Join[Range[18],{20},Range[23,103]]
$\endgroup$
2
$\begingroup$
Range@100 /. x_ /; x >= 20 -> x + 3 /. 19 -> 20
$\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.