2

i want to add a variable amount of variables to manipulate, but i got stuck at one point and can't figure out a solution (even after reading here for hours...).

I have a function (e.g. here a gaussian):

f[x_, a_,μ_,σ_] := a Exp[-(x - μ)^2/(2 σ^2)]/(Sqrt[2 Pi] σ)

and define now a sum of these function, which i would like to plot using manipulate:

n=3;
test = {A[#], μ[#], σ[#], m[#]} & /@ Range[n];
func = f[x, ##] & @@@ test;

Setting initial values like this:

initialvalues = {50, 5, 20, 50, 50, 40, 100, 80, 20};
values = Partition[initialvalues, n];
rangelow = values*0.7;
rangehigh = values*1.3;

Now i want to plot this, after setting initial values with manipulate, e.g. like this:

With[{func = func},
    Manipulate[
        Show[Plot[func, {x, 0, 100}, PlotRange -> All]],
    'List of manipulate arguments'
        ]
]

With a list like this:

testlist = 
 Flatten[{{{A[#], values[[#, 1]]}, rangelow[[#, 1]], 
  rangehigh[[#, 1]]}, {{μ[#], values[[#, 2]]}, 
  rangelow[[#, 2]], 
  rangehigh[[#, 2]]}, {{σ[#], values[[#, 3]]}, 
  rangelow[[#, 3]], rangehigh[[#, 3]]}} & /@ Range[n], 1]

But I can't figure out how to remove the outer bracketsand there should be a better solution.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
newbie008
  • 23
  • 2

1 Answers1

5

One can slightly rewrite your code and obtain a nice Manipulate

f[x_, a_, μ_, σ_] := a Exp[-(x - μ)^2/(2 σ^2)]/(Sqrt[2 π] σ)

n = 3;
vars = Through@{a, μ, σ}@# & /@ Range[n];
func = f[x, ##] & @@@ vars;

values = {{50, 5, 20}, {50, 50, 40}, {100, 80, 20}};
rangelow = 0.7 values;
rangehigh = 1.3 values;

With[{func = func}, 
 Manipulate[Plot[func, {x, 0, 100}, PlotRange -> All], ##] & @@ ({{#, #2}, ##3} & @@@ 
    Flatten[{vars, values, rangelow, rangehigh}, {{2, 3}}])]

enter image description here

There is two basic techniques to inject a list of variables:

  • function[..., ##] & @@ variables
  • With[{vars = Sequence @@ variables}, function[..., vars]]
Gerli
  • 1,051
  • 6
  • 12
ybeltukov
  • 43,673
  • 5
  • 108
  • 212