4

I want to access the fit-parameters of a NonlinearModelFit. Here is the code

model = a*Cos[b*t + c];
fit = NonlinearModelFit[data, model, {a, b, c}, t, Method -> NMinimize]

When I use the command:

fit["BestFitParameters"]

the values are returned in the following format:

{a -> 1, b -> 2, c -> -3}

Now i want to store the value of a in a variable x

x=fit["BestFitParameters"][[1]]

but this gives

x= a -> 1

No I want to know how I can resolve the "-> - Operator" to obtain

x=1

Thanks in advance!

neon
  • 43
  • 3

3 Answers3

3

Well, you could write

x = a/.{a -> 1, b -> 2, c -> -3}

which will assign the value of a to x.

I'm not entirely sure that you should do this, you could simply store the list of rules in a variable and extract the bits from it as and when you want to.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
2

Might I suggest a yet another approach:

C1fitparameters = 
Table[{C1fit["BestFitParameters"][[i, 1]], C1fit["BestFitParameters"][[i, 2]]}, 
{i, 1, Length[C1fit["BestFitParameters"]]}]

Which returns a list:

{{A, 5.11419}, {Beta, 14.2637}, {Omega_0, 174.118}, {Phi, -0.117246}}

So to access either the variable name:

C1fitparameters[[1, 1]]

returns A. And:

C1fitparameters[[1, 2]]

returns the value of A which is 5.11419. Voila.

1

You want

x = fit["BestFitParameters"][[1]][[2]]

This retrieves the right-hand-side of a->1. using x = fit["BestFitParameters"][[1]][[1]] would retrieve the left-hand-side ("a", in this case)

aquirdturtle
  • 2,038
  • 26
  • 20
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Dec 01 '16 at 08:36