Maxima - using square brackets in variable names
-
14-07-2021 - |
Question
In Maxima, I'd like to numerically solve a system of differential equations in an arbitrary number of variables x[1]
... x[n]
, using the rk
function. I use square brackets in the variable name so that I can index the variables in a for loop. Here is an example call to rk
when n = 2:
rk([derivativeOfX[1],-2*x[1]+x[2],derivativeOfX[2],x[1]-2*x[2]], [X[1],derivativeOfX[1],X[2],derivativeOfX[2]], [1,1,2,0], [t,0,10,0.1])
Unfortunately, I get the error:
define: in definition of f_rk_4, found bad argument X[1]
If I manually replace X[1]
with x1
and X[2]
with x2
, the error goes away:
rk([derivativeOfX1,-2*x1+x2,derivativeOfX2,x1-2*x2], [x1,derivativeOfX1,x2,derivativeOfX2], [1,1,2,0], [t,0,10,0.1]);
It seems that rk
doesn't like the square brackets in the variable names, but I need them in order to index the variables in a for loop. What should I do?
Solution
A simple solution is to have two sets of variables. In the loop you use x[1] and x[2]. Before your rk(...) expression, set x1 equal to x[1] and x2 equal to x[2]. Call rk. Then store x1 in x[1] and x2 in x[2].
Note that you can generate variable names using concat. For example concat('x, 1) will produce the symbol x1.