The OP in the question, How to return the unevaluated variable names from a list of variables which have been declared, raised a side issue in an edit, whose solution seemed far afield of the main question. I thought I would post my take on the question and self-answer, too.
The question is how to have an indeterminate number of variables in a Manipulate
, each controlled by a slider and be able to update these values in the code of the Manipulate
, say, by some numerical routine such as FindFit
. There are several Q&A on a coding a variable number of variables (see below), but none I could find also addressed updating the indefinite number of controls.
Here is a example, modified from the linked question, that has a variable number of sliders. The sliders appear to work, but the button that executes FindFit
causes errors and the model[]
function is not plotted, even on the initial evaluation.
ClearAll[testplotfit, model, a, b];
data = Table[{x, 8 x^3 - 7 x^2 - 10 x + 1 + RandomReal[{-5, 5}]}, {x, -2, 2, 0.1}];
model[v_, terms_, x_] := FromDigits[Reverse@Array[v, terms], x];
SetAttributes[testplotfit, HoldRest];
testplotfit[terms_, data_] :=
Manipulate[
Column[{
Dynamic[Button["Compute", (* FindFit[] button *)
Block[{x}, With[{sol = FindFit[
data,
model[b, terms, x],
Transpose@{Array[b, terms], Array[a, terms]},
x]},
Do[a[i] = b[i] /. sol, {i, terms}]]]
]],
Show[ (* plots: *)
Plot[ (* model *)
model[a, terms, x] /.
Array[HoldPattern[a[#]] -> a[#] &, terms],
{x, Min@data[[All, 1]], Max@data[[All, 1]]},
PlotStyle -> Black, PlotRange -> MinMax /@ Transpose@data],
ListPlot[data, PlotStyle -> Red], (* data *)
ImageSize -> 300, PlotRangePadding -> Scaled[.05]
]
}],
Evaluate[ (* controls *)
Sequence @@ Table[With[{i = i}, {{a[i], 1, Subscript["a", i]}, -10, 10,
Appearance -> "Open"}], {i, 2}]]
]
Example:
testplotfit[2, data]
What would be even better is if I could vary the number of terms
with a slider and have the number of sliders change automatically.
A variable number of sliders and other controls comes up in several Q&A (and there are more):
Manipulate with variable number of sliders plus variable number of functions
Manipulate with a variable number of sliders (answers only in terms of
DynamicModule
and notManipulate
)Mathematica Manipulate with macros AND variable number of controls (persistence desired)