How do I assign a value, say 7 or "t", to a[1, 2][[3]]?

a[1, 2][[3]] = 7


a[1, 2][[3]] = "t"

both give

Set::setps: a[1,2] in the part assignment is not a symbol

I have looked here and here, but both questions ask more complicated questions and I'm afraid I'm none the wiser.

  • 1
    $\begingroup$ Perhaps a[1, 2] = MapAt[7 &, a[1, 2], {3}] or a[1,2] = ReplacePart[a[1, 2], 3 -> 7]? $\endgroup$ – kglr Sep 9 '17 at 18:55
  • 3
    $\begingroup$ You can't do this. Part assignments are not supported for indexed variables. This is a fundamental limitation, there is no way around it, if you want to keep assignments as O(1) operations. Note that the suggestions which use things like MapAt or RepalcePart will reassign entire list. Note also that a[1,2][3] is a completely different thing - it is a nested indexed variable, while a[1,2][[3]] is a part 3 of the value of indexed variable a[1,2]. $\endgroup$ – Leonid Shifrin Sep 9 '17 at 18:56
  • 1
    $\begingroup$ Fundamentally, indexed variables are stored in a kind of hash table (DownValues or SubValues), which are rule-based. This is why this kind of complex part assignments are not allowed there. You can use an association instead, where you will be able to do something similar to what you want. $\endgroup$ – Leonid Shifrin Sep 9 '17 at 19:01
  • 1
    $\begingroup$ It's not really clear what you want to achieve. Can you give a simple example where you show what the expected result (or effect) is? I suspect that everyone in the comments above misunderstood what you wanted, but I'm not sure. $\endgroup$ – Szabolcs Sep 9 '17 at 19:02
  • 3
    $\begingroup$ When you define a[1,2,3] = 7, you don't define an array. Instead, you define an indexed variable. They are different objects. To define an array, you need to use List, like a = {{{1,2,3}, {4,5,6}}, {{7,8,9},{10,11,12}}}, which is a 3D array. Then you can do a[[1,2,3]] = 7, and that would replace the number 6 in that array by 7. But you must have an array stored in some variable first, to make such part assignments. $\endgroup$ – Leonid Shifrin Sep 9 '17 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy