I'm using Mathematica to generate some data, and I'm having some difficulty understanding how my intuition from "regular programming" should transfer over. The code that I'm writing does the following:
- Generates a 2D plot, which is itself a function of several different parameters (call these parameters 'X').
- Fits the plot to another function, and extracts the fit parameters (called 'A').
- Writes both X and A to a file.
This whole process is a dozen or so lines of code (since generating the plot takes a few steps). I would like to repeat this process for many different instances of 'X'. In a more standard programming language, I would simply wrap the above three steps in a function of 'X', and then put it in a for loop that loops over different values of 'X.' My understanding of Mathematica is that for loops are discouraged, and the 'Do' function is more proper. However, all the uses of Do that I could find usually just involve repeated evaluations of a single expression, rather than several lines of code that must be executed sequentially. What is the "correct" way of accomplishing the above task in Mathematica?
EDIT: Here is a minimal example of what I want to do:
H[a_, b_, c_, x_] := a x^2 + b x + c;
a = 1;
b = 2;
c = 3;
fitData = Table[H[a, b, c, x], {x, 0, 20}];
fitParams = FindFit[fitData, d x^2 + f x + g, {d, f, g}, x];
data = {a, b, c, d, f, g} /. fitParams;
Export[data, "data.txt"]
and in this case, I would like to loop over many different values of a, b, and c.
CompoundExpression
with semicolons anywhere in place of a single expression. $\endgroup$findData[a_, b_, c_] := Module[{fitData, fitParams, d, f, g, x}, fitData = Table[H[a, b, c, x], {x, 0, 20}]; fitParams = FindFit[fitData, d x^2 + f x + g, {d, f, g}, x]; {a, b, c, d, f, g} /. fitParams]
-- Well, your example code didn't show a 2DPlot[]
per se, so I'm assuming theTable[]
is what you meant. And I skipped theExport
, since I think separating the data generation from the I/O makes handling the data more flexible.. $\endgroup$