# Using “If” statement to change a list values

I have a question that would be pretty trivial in almost any other language but is giving me a massive headache in Mathematica.

I am trying to construct an If statement check on one variable that I want to use to modify another variable. The problem is that while it works perfectly well if I ask it to test a single element of a list for the condition it works fine:

Sample = {1, 65, -40, 120};
Sample2 = {5, 10, 15, 20};

If[Sample[[1]] < 60, Sample2[[1]] + 20, Sample2[[1]]]


25

But for the life of me I cannot figure out the proper syntax to ask it to iterate through the entire list to check each element of the list Sample being used in the If statement and then update the corresponding Sample2 list element.

If[Sample < 60, Sample2 + 20, Sample2]


If[{1, 65, -40, 120} < 60, Sample2 + 20, Sample2]

If[Sample[[All]] < 60, Sample2[[All]] + 20, Sample2[[All]]]


If[{1, 65, -40, 120} < 60, Sample2[[All]] + 20, Sample2[[All]]]

Etc, etc...

I feel like there must be a very simple and streamlined solution to this simple problem that I am just overlooking, but I have been up and down the documentation as well as other stackexchange pages and nothing is jumping out at me. I've spent way too much time on this as is...

Use MapThread

MapThread[If[# < 60, #2 + 20, #2] &, {Sample, Sample2}]


or alternatively

Sample2 + 20 Boole[Thread[Sample < 60]]

• I knew there had to be an elegant solution! Thank you so much. Another tool to add to my Mathematica toolbox! – Ed McClain Jan 29 '18 at 18:46

Either

Sample = {1, 65, -40, 120};
Sample2 = {5, 10, 15, 20};

Do[If[Sample[[i]] < 60, Sample2[[i]] = Sample2[[i]] + 20, Sample2[[i]]], {i, 1, Length[Sample]}]

Sample2


{25, 10, 35, 20}

or

Sample = {1, 65, -40, 120};
Sample2 = {5, 10, 15, 20};

Sample2 =
Table[If[Sample[[i]] < 60, Sample2[[i]] + 20, Sample2[[i]]], {i, 1, Length[Sample]}]


also gives

{25, 10, 35, 20}

• Thank you! I had a feeling there was a way to do it with "Do" as well but I couldn't get it to work. – Ed McClain Jan 29 '18 at 19:00
fun[a_, b_] := If[a < b, b + 20, b]
SetAttributes[fun, Listable]
fun[sample, sample2]


{25, 10, 35, 20}

give to the function the attribute Listable

another option :

test = Transpose[{sample, sample2}]
If[# === Sort[#], #[[2]] + 20, #[[2]]] & /@ test


Also

With[{p = UnitStep[60 - Sample]},  Sample2 + p 20]


{25, 10, 35, 20}

Inner[If[# < 60, #2 + 20, #2] &, Sample, Sample2, List]


{25, 10, 35, 20}

• Thank you @corey979, Corrected now. – kglr Jan 30 '18 at 10:31