Effacer les filtres
Effacer les filtres

help with curve fitting with a data function

4 vues (au cours des 30 derniers jours)
sofia
sofia le 6 Avr 2023
Hello,
I'm new to matlab and I'm trying to do a curve fit on my data. However the fit I get isn't what I want, I'm expecting a sinusoidal kind of fit, the graph should look something like how it would if it had as parameter a=0.22 and b=2.69.
this are the data in the 'ottica10.dat' , followed by the script
0 0.93662268
0.166666667 0.768673057
0.333333333 0.440962327
0.5 0.210683072
0.666666667 0.13586155
0.833333333 0.350939133
0.916666667 0.595077789
1 0.741090275
1.166666667 0.924650127
1.333333333 0.798268208
1.67 0.149390082
1.836666667 0.117268597
2.003333333 0.333450767
2.17 0.631289664
2.336666667 0.739983858
2.503333333 0.603385353
2.67 0.396734567
2.836666667 0.113693139
3.003333333 0.130192654
% Load data from file
data = load('ottica10.dat');
Error using load
Unable to find file or directory 'ottica10.dat'.
% Define the model function
M = 2;
myfun = @(p,x) 1/M * exp(-p(1) * 0.5 .* x) .* abs(sin(M*p(2) .* x * 0.5)./(sin(0.5 * p(2) .* x) + 1e-10));
% Set initial values for parameters
p0 = [1, 1];
% Fit the model to the data
params = lsqcurvefit(myfun, p0, data(:,1), data(:,2));
% Generate points for curve plot
x = linspace(min(data(:,1)), max(data(:,1)), 100);
y = myfun(params, x);
% Plot the data and the fitted curve
plot(data(:,1), data(:,2), 'o', x, y);
xlabel('x');
ylabel('y');
legend('Data', 'Fitted curve');

Réponse acceptée

Davide Masiello
Davide Masiello le 6 Avr 2023
Just needed better initial guesses, I think
data = readmatrix('ottica10.txt');
M = 2;
myfun = @(p,x) 1/M*exp(-p(1)*0.5*x).*abs(sin(M*p(2).* x * 0.5)./(sin(0.5 * p(2) .* x) + 1e-10));
p0 = [0.5, 5];
params = lsqcurvefit(myfun, p0, data(:,1), data(:,2))
Local minimum possible. lsqcurvefit stopped because the final change in the sum of squares relative to its initial value is less than the value of the function tolerance.
params = 1×2
0.3419 5.3360
% Generate points for curve plot
x = linspace(data(1,1),data(end,1), 100);
y = myfun(params,x);
% Plot the data and the fitted curve
plot(data(:,1), data(:,2), 'o', x, y); hold on
xlabel('x');
ylabel('y');
legend('Data', 'Fitted curve');

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with Curve Fitting Toolbox dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by