5
$\begingroup$

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)

$\endgroup$

3 Answers 3

3
$\begingroup$
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}}

Additional methods:

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}}
$\endgroup$
4
$\begingroup$

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

$\endgroup$
1
  • 1
    $\begingroup$ 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? $\endgroup$
    – lineage
    Commented Sep 7, 2020 at 13:37
1
$\begingroup$
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}}

$\endgroup$
1
  • $\begingroup$ may pass r directly into SubsetMap skipping ApplyTo; SubsetMap[vals &, r, pos] (as shown in kglr's answer) $\endgroup$
    – lineage
    Commented Feb 25 at 4:43

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.