# Set value in a list at given position

Consider

r = Array[Total[{##}] &, {3, 3}]
(*{{2, 3, 4}, {3, 4, 5}, {4, 5, 6}}*)
pos = {{1, 1}, {2, 2}};
vals={100,200}


This

r[[pos[[1]]]]=vals[[1]]


doesn't chnage the value of r at position pos[[1]]? How to achieve this?

(reads are being performed using Extract)

r[[## & @@ pos[[1]]]] = vals[[1]];
r

{{100, 3, 4}, {3, 4, 5}, {4, 5, 6}}

r = Array[Plus, {3, 3}];
Do[r[[## & @@ pos[[i]]]] = vals[[i]], {i, 2}];
r

{{100, 3, 4}, {3, 200, 5}, {4, 5, 6}}


r = Array[Plus, {3, 3}];
MapThread[(r[[## & @@ #]] = #2) &, {pos, vals}];
r

 {{100, 3, 4}, {3, 200, 5}, {4, 5, 6}}

r = Array[Plus, {3, 3}];
(r[[#, #2]] = #3) & @@@ (Flatten /@ Transpose[{pos, vals}]);
r

 {{100, 3, 4}, {3, 200, 5}, {4, 5, 6}}

r = Array[Plus, {3, 3}];
r = SubsetMap[vals &, r, pos];
r

 {{100, 3, 4}, {3, 200, 5}, {4, 5, 6}}

r = Array[Plus, {3, 3}];
r = MapAt[Last[vals = RotateLeft[vals]] &, pos] @ r;
r

 {{100, 3, 4}, {3, 200, 5}, {4, 5, 6}}


ReplacePart[r, Thread[pos -> vals]]

• thnx for the sol but this doesn't set the value of r in place.....rather generates a new one.... is it performant enough to do $r=ReplacePart[r, pos -> val]$ say order len@r times for random pos? Sep 7, 2020 at 13:37
r = Array[Total[{##}] &, {3, 3}];

pos = {{1, 1}, {2, 2}};

vals = {100, 200};


To set the value of r in place we can use ApplyTo (new in 12.2) followed by the operator form of SubsetMap

r //= SubsetMap[vals &, pos];

r


{{100, 3, 4}, {3, 200, 5}, {4, 5, 6}}

• may pass r directly into SubsetMap skipping ApplyTo; SubsetMap[vals &, r, pos] (as shown in kglr's answer) Feb 25 at 4:43