1
$\begingroup$

I do not really understand why this:

a = {1, 2, 3};
a[[1]] = 3;
a

{3,2,3}

works as desired, but this does not:

b[1] = {1, 2, 3};
b[1][[1]] = 3;
b[1]

Set::setps: b[1] in the part assignment is not a symbol.

Can I not treat variables with arguments like 'normal' variables?

$\endgroup$
1
  • 1
    $\begingroup$ closely related: 148387 $\endgroup$
    – Kuba
    Oct 22, 2019 at 9:20

1 Answer 1

1
$\begingroup$

You can use ReplacePart:

ClearAll[b]
b[1] = {1, 2, 3};
b[1] = ReplacePart[ b[1], 1 -> 3];
b[1]

{3, 2, 3}

Alternatively, MapAt:

ClearAll[b]
b[1] = {1, 2, 3};
b[1] = MapAt[3 &, b[1], {1}];
b[1]

{3, 2, 3}

$\endgroup$
5
  • $\begingroup$ Interesting thank you. What would I do If I wanted to set a column in a two Dimensional array? Like this: a = ConstantArray[1, {10, 10}] a[[;; , 3]] = ConstantArray[2, 10]; a $\endgroup$
    – Mr Puh
    Oct 22, 2019 at 9:33
  • $\begingroup$ @MrPuh, the code in your comment works as expected. $\endgroup$
    – kglr
    Oct 22, 2019 at 9:35
  • $\begingroup$ yeah, I mean in the sense of the question, I would want something like this now: a[1] = ConstantArray[1, {10, 10}] a[1][[;; , 3]] = ConstantArray[2, 10]; a[1] $\endgroup$
    – Mr Puh
    Oct 22, 2019 at 9:43
  • 1
    $\begingroup$ @MrPuh, you can do ClearAll[a];a[1] = ConstantArray[1, {10, 10}] ;a[1]=MapAt[ 2&,a[1], {All,3}];a[1] or ClearAll[a];a[1] = ConstantArray[1, {10, 10}] ; a[1]=ReplacePart[ a[1], {_,3}->2];a[1] $\endgroup$
    – kglr
    Oct 22, 2019 at 9:53
  • $\begingroup$ ... you can also use SubsetMap: ClearAll[a];a[1] = ConstantArray[1, {10, 10}] ; a[1]=SubsetMap[ConstantArray[2,10]&,a[1], {All,3}];a[1] $\endgroup$
    – kglr
    Oct 22, 2019 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.