2

I want to fit a function to some data and inside the function there's a list

here's my data

Ei = {{1, -0.00006636511699298353`}, {2, -0.00007582534298933297`}, \
{3, -0.00008658039298836684`}, {4, -0.00009882137899808185`}, {5, \
-0.0001127647090015671`}, {6, -0.00012865092799074773`}, {7, \
-0.00014674610198994742`}, {8, -0.00016733831999715676`}};

the list

racc = {6.0, 5.9, 5.8, 5.7, 5.6, 5.5, 5.4, 5.3, 5.2, 5.1};

and my function

U[r_] := ecc (1 - (racc[[r]] - Exp[-Acc (1 - rscc)])^2);

But mathematica shows my function as

ecc (1 - (-E^(-Acc (1 - rscc)) + {6., 5.9, 5.8, 5.7, 5.6, 5.5, 5.4, 
   5.3, 5.2, 5.1}[[r]])^2)

Though in someway it can understand it and give the result for function

U[3] /. {ehh -> 1, Ahh -> 1, rshh -> 1, ech -> 1, Achrsch -> 1, 
ecc -> 1, Acc -> 1, rscc -> 1};

-22.04

And it's able to fit it, although an giving an error

sol = FindFit[Ei, U[r], {ecc, Acc, rscc}, r]

Part::pspec: Part specification r is neither an integer nor a list of integers. >>    
{ecc -> 3.45136*10^-6, Acc -> -21.5489, rscc -> 2.67028}

It can not Plot it

P2 = Plot[U[r] /. sol, {r, 1, 8}];
Part::pspec: Part specification 1.000143` is neither an integer nor a list of integers. >>
Part::pspec: Part specification 1.1430001428571428` is neither an integer nor a list of integers. >>
Part::pspec: Part specification 1.2858572857142856` is neither an integer nor a list of integers. >>
General::stop: Further output of Part::pspec will be suppressed during this calculation. >>

Does anybody have an idea how to put a matrix or list inside a function?

Sarah Aria
  • 302
  • 3
  • 8

2 Answers2

2

Try FromDigits[]

U[r_] := ecc (1 - (FromDigits[racc, r] - Exp[-Acc (1 - rscc)])^2);
2

I think the issue is that your function U is defined only for integer r, whereas FindFit would want to sample the function at intermediate points as well. In this case, you can build the least squares by hand. Additionally, your choice seems to be a poor fit; the vector racc decreases with its index, which makes your U increase so you won't get a good fit. Just for fun, I tried another fitting function with racc Reversed.

bigU[r_] := ecc (1 - (racc[[r]] - Exp[-Acc (1 - rscc)])^2)
bigU2[r_] := ecc (1 - (Reverse[racc][[r]] - ex)^2)

sol = NMinimize[Total[(bigU[#[[1]]] - #[[2]])^2 & /@ Ei], {ecc, Acc, rscc}];
sol2 = NMinimize[Total[(bigU2[#[[1]]] - #[[2]])^2 & /@ Ei], {ecc, ex}];

ListPlot[{Ei, {#, bigU[#] /. sol[[2]]} & /@  Ei[[All, 1]], 
          {#, bigU2[#] /. sol2[[2]]} & /@ Ei[[All, 1]]}, Joined -> {False, True, True}]

plot

b.gates.you.know.what
  • 20,103
  • 2
  • 43
  • 84