1
$\begingroup$

Task: Finding roots in loop

t = List[1, 2, 3, 4, 5]
fx[x_] := a*x^2 - 5
List[Do[Print[FindRoot[fx[k] == 1, {a, 1}]], {k, 0, 5}]]

Output: Currently the output is as follows:

 {a-> 6}
 {a-> 1.5}

and so forth

But I want to have the values of a in a List in order to perfom further tasks (Plotting root of f_a against a)

$\endgroup$
  • 3
    $\begingroup$ Using Table and Map are things you should get really comfortable with in general, so look them up in documentation center, and browse around here a bit: wolfram.com/support/learn $\endgroup$ – ssch Feb 11 '13 at 16:06
  • 1
    $\begingroup$ Please try to avoid procedural loops $\endgroup$ – Dr. belisarius Feb 11 '13 at 16:31
  • 2
    $\begingroup$ Don't use Print to generate values that you want to process further on. ssch has good advice. The List you use doesn't make sense here either. Another advice: Generally you should not define functions that have more dependencies than shown by the variables in the call pattern. In your case, the function depends on a as well, but that is not made explicit. $\endgroup$ – Sjoerd C. de Vries Feb 11 '13 at 16:48
6
$\begingroup$

You have many many options. Here are just two:

Table[FindRoot[fx[k] == 1, {a, 1}], {k, t}]

Or

FindRoot[fx[#] == 1, {a, 1}] & /@ t

Here is one way to make a plot of t vs the roots:

pts = Table[{k, a /. FindRoot[fx[k] == 1, {a, 1}]}, {k, t}];
ListLinePlot@pts

Example plot of t vs roots

$\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.