1
$\begingroup$

I am trying to run this code using a single loop. Values for variables $a$ and $b$ are user defined (not random data). Below is my code,

ClearAll;
f[a_, b_] := a*x^2 + b*x + 12 - a - b;

a1 = 1; b1 = 2;
plot1 = Plot[f[a1, b1], {x, 0, 10}, 
PlotLabel -> 
Style[Framed[
  "Curve Plot\n" <> " a=" <> ToString[a1] <> " b=" <> 
   ToString[b1] ] ]];

a2 = 2; b2 = 2;
plot2 = Plot[f[a1, b1], {x, 0, 10}, 
PlotLabel -> 
Style[Framed[
  "Curve Plot\n" <> " a=" <> ToString[a2] <> " b=" <> 
   ToString[b2] ] ]];

a3 = 1; b3 = 3;
plot3 = Plot[f[a1, b1], {x, 0, 10}, 
PlotLabel -> 
Style[Framed[
  "Curve Plot\n" <> " a=" <> ToString[a3] <> " b=" <> 
   ToString[b3] ] ]];

a4 = 1; b4 = 4;
plot4 = Plot[f[a1, b1], {x, 0, 10}, 
PlotLabel -> 
Style[Framed[
  "Curve Plot\n" <> " a=" <> ToString[a4] <> " b=" <> 
   ToString[b4] ] ]];
plottotal = 
Column[{GraphicsGrid[{{plot1, plot2}, {plot3, plot4}}, 
PlotLabel -> Style[Framed["Data Plots"], 18, Black, Bold], 
ImageSize -> 1180]}]

Data $a$ and $b$ can be in matrix, grid or table format. How to run a loop from set of input data?

$\endgroup$
2
$\begingroup$

One way might be to put your input in a matrix and then map over it

ClearAll;
f[a_,b_]:=a*x^2+b*x+12-a-b;
input={{1,2},{2,2},{1,3},{1,4}};

plots={a=#[[1]];b=#[[2]];Plot[f[a,b],{x,0,10},
     PlotLabel->Style[Framed["Curve Plot\n"<>" a="<>
     ToString[a]<>" b="<>ToString[b]]]]}&/@input;

GraphicsGrid[Partition[Flatten@plots,2],
    PlotLabel->Style[Framed["Data Plots"],18,Black,Bold],ImageSize->500]

Mathematica graphics

$\endgroup$
1
$\begingroup$

You can do it with Apply (@@@). First, I've redefined your function just because it bothers me to not have x as an argument:

f[x_, a_, b_] := a*x^2 + b*x + 12 - a - b;

Set up your list of {a, b} parameters:

paramlist = {{1, 2}, {2, 2}, {1, 3}, {1, 4}};

Then you can make your Plot a pure function and Apply it to each element in paramlist:

plots = Plot[f[x, #1, #2], {x, 0, 10}, 
    PlotLabel -> Style[Framed[
       "Curve Plot\n" <> " a=" <> ToString[#1] <> " b=" <> ToString[#2]]]
    ] & @@@ paramlist;

This gives you back a list of your plots, which you can then Partition into two columns (however many plots there are in the list) and put it into a GraphicsGrid. (I don't think the Column part was really necessary.)

GraphicsGrid[Partition[plots, 2, 2, {1}, {}], 
 PlotLabel -> Style[Framed["Data Plots"], 18, Black, Bold], 
 ImageSize -> 750]

enter image description here

The extra arguments in Partition[plots, 2, 2, {1}, {}] are just so that it all still works if there are an odd number of plots, and the last one doesn't get cut off.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.