V 12.1 on windows 10.
I am still learning how to use Associations.
This is very strange. I wanted to change field in association using AssociateTo
. When the association is inside a list, the replacement does not work. This is better shown with MWE
ClearAll[y, x];
ode1 = <|"ode" -> y[x] == 0, "y" -> y, "x" -> x|>;
ode2 = <|"ode" -> y[x] + x == 1, "y" -> y, "x" -> x|>;
sol = {y[x] == 999, y[x] == -20};
ODEs = {ode1, ode2}; (*list of Associations *)
Now to replace field ode
in ode1
by y[x] == 999
, I did
AssociateTo[ ODEs[[1]], "ode" -> sol[[1]] ]
But this gives
{<|"y" -> y, "x" -> x, "ode" -> y[x] == 999|>,
<|"ode" -> x + y[x] == 1, "y" -> y, "x" -> x|>}
Notice it returned not just the first part of the list, but it also returned back ODEs[[2]]
with it!
This causes big problems. (Example of big problem is given below if needed)
But when doing
AssociateTo[ ode1, "ode" -> sol[[1]]]
It works, and returns the expected change to the association
<|"ode" -> y[x] == 999, "y" -> y, "x" -> x|>
But I want to do this change when the Associations are inside a list.
Question is: When does AssociateTo[ ODEs[[1]], "ode" -> sol[[1]] ]
return all contents of the list and not just the part affected?
Appendix
Example why the above behavior is causing a problem is this. MapThread fails now
ClearAll[y,x];
ode1 = <|"ode" -> 5 == y[x], "y" -> y, "x" -> x|>;
ode2 = <|"ode" -> 5 == y[x] + x, "y" -> y, "x" -> x|>;
sol = {y[x] == 19, y[x] == 29}; (*new values to update with *)
ODEs = {ode1, ode2}; (*list of Associations *)
MapThread[ AssociateTo[#2, "ode" -> #1] &, {sol, ODEs}]
And I think this error is related to the main question above.
I tried Evaluate, and looked at How does MapThread work with Associations and looked at AssociationThread
but so far no solution I could see for the main question above.
I can for now work around this as follows
Last@Reap@Do[
tmp = ODEs[[n]];
Sow[ AssociateTo[tmp, "ode" -> sol[[n]]]]
,
{n, 1, Length[ODEs]}
]
Which gives what I want
{<|"y" -> y, "x" -> x, "ode" -> y[x] == 999|>,
<|"ode" -> y[x] == -20,"y" -> y, "x" -> x|>}
References
https://reference.wolfram.com/language/ref/AssociateTo.html
https://reference.wolfram.com/language/ref/Association.html
https://reference.wolfram.com/language/ref/AssociationThread.html