Mathematica Asked by Rupesh on July 4, 2021
I want to fit an ellipse model to a data. This sample data I extracted from a simple parametric plot of 2 Sin[t], Cos[t]
(Let’s say, I don’t know that) and I want to fit my model of an ellipse to this data. This is what I have tried:
Sample data:
data = Flatten[ Cases[ParametricPlot[{Cos[t], 2 Sin[t]}, {t, 0, 2 Pi}], Line[data_] :> data, Infinity], 1];
Model:
x^2/a^2 + y^2/b^2 == 1
f[x_]:=Sqrt[(1 - x^2/a^2) b^2];
and,
fit = NonlinearModelFit[data,f[x], {a,b}, x]
It throws me complex infinity error and I am not able to solve it. Any help is appreciated.
Since the model is of the form f(x,y) = 1, arrange the data as {{x,y,1} . . } for the fit:
(* make some data *)
(* the data is of the form { {x,y,1}, . . . } *)
eq = x^2/4 + y^2/9 == 1;
y[xx_] := y /. Solve[eq /. x -> xx, y]
points = Union[
Flatten[Table[{x, y[x]}, {x,
Range[-2, 2, .1]}] /. {x_, {y1_, y2_}} -> {{x, y1, 1}, {x, y2,
1}}, 1]];
(* plot the data *)
ListPlot[points[[All, {1, 2}]]]
(* the general model *)
model = x^2/a^2 + y^2/b^2;
(* fit the data *)
fit = NonlinearModelFit[points, model, {a, b}, {x, y}];
fit["BestFitParameters"]
(* {a[Rule]2.`,b[Rule]2.999999999953799`} *)
Correct answer by David Keith on July 4, 2021
Here is a SingularValueDecomposition
approach following @Danial Lichtblau's answer to 51549.
mean = Mean[data];
newpts = Map[# - mean &, data];
{uu, ww, vv} = SingularValueDecomposition[newpts, 2];
ListPlot[uu, AspectRatio -> Automatic]
rsqr = Mean[Map[#.# &, uu]];
{nx, ny} = Inverse[vv.ww].({x, y} - mean);
expr = Expand[nx^2 + ny^2] == rsqr;
expr = MultiplySides[expr, 1/expr[[2]]] // Expand
reg = ImplicitRegion[expr[[1]] <= expr[[2]] 1.1, {x, y}];
ContourPlot[Evaluate@expr, {x, y} [Element] reg,
Epilog -> {Red, PointSize[Medium], Point[data]},
AspectRatio -> Automatic]
Answered by Tim Laska on July 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP