Setting Variables Element-wise in a Matrix in Mathematica
February 2 2016 in Mathematica, Programming | Tags: | Author: Christopher Rackauckas
This is the latest entry on tip, tricks, and hacks in Mathematica. In my latest problem I need to solve for the components of many matrices using optimization algorithms. Mathematica does not allow one to straight pass matrices into the algorithms, so one has to perform the algorithms on variables that stand in for the components. This is what I did with the matrix $$A1$$, solving for $$A[i,j]=A1ij$$. That was all fine and dandy until I needed to set some of those matrices to constants. I could do a bunch of set commands all lined up, i.e.
A011 = 2; A021 = 1.4; ...
But that would be inelegant and hard to maintain. Luckily, I found a way to specify them as matrices. I attach a screenshot to show it in all its GUI glory (click on it to enlarge it):
What it does it flatten the matrix and constant into lists of variables, and uses set on the lists to apply setting component-wise. This is one useful hack, but what if I need to keep adding the constants from the results of different lists? I found that you could use Mathematica’s key/value constructs for doing this. For example, we can pull the appropriate value out of the lists as follows:
Thus I can fill the matrix of constants using these <|list|>[Key] commands to automatically put the values of previous runs (stored in the list previous) into the matrix of constants.