Message Boards Message Boards

Make a set of functions using loops?

Posted 8 years ago

I'm trying to make a set of Gaussians, then I want to plot each gaussian seperately and compare them to how they look combined. I currently have it where I only look at the combined case:

G[x_] := Sum[a[i] Exp[ -(x - b[i])^2/(2 c[i]^2)], {i, 10}]; Do[Print[{a[i] = RandomInteger [{1, 10}], b[i] = RandomInteger[{-10, 10}], c[i] = RandomInteger[{1, 10}]}], {i, 10}] Plot[{G[x]}, {x, -10, 10}, PlotRange -> All]

Basically I'm making a total function G[x] and I'm summing 10 randomly generated functions. My end goal is to enter my own values but for now this will work. Now I want to take these random functions and name them somethings like A1[x], A2[x] A3[x], or however the syntax will allow so I can easily tell function 1 is related to a[1],b[1],and c[1]. Then I want to plot all the Ai[x] functions along with the G[x] function so I can see each individual functions contributio. What kind of look do i need to make to generate this subset of functions that comprise G[x]?

POSTED BY: Nicholas Breslin
2 Replies

Or this:

ClearAll[a,b,c,F,G,list,n];
n = 10;
a = RandomInteger [{1, 10},n];
b = RandomInteger[{-10, 10},n];
c = RandomInteger[{1, 10},n];
F[i_][x_Real]:=a[[i]] Exp[ -(x - b[[i]])^2/(2 c[[i]]^2)]
G[x_Real] := Sum[F[i][x], {i, n}];

list=Append[Table[F[i][x],{i,n}],G[x]];
Plot[Evaluate@list, {x, -10, 10}, 
PlotRange -> All,PlotLegends->list]

(no need for loops - avoid them if possible ;)

Something like this?

Do[Print[{a[i] = RandomInteger[{1, 10}], 
   b[i] = RandomInteger[{-10, 10}], c[i] = RandomInteger[{1, 10}], 
   Subscript[A, i][x_] = a[i] Exp[-(x - b[i])^2/(2 c[i]^2)]}], {i, 10}]
G[x_] = Sum[Subscript[A, i][x], {i, 10}]
Plot[Evaluate[
  Join[Table[Subscript[A, i][x], {i, 10}], {G[x]}]], {x, -10, 10}]
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract