Effacer les filtres
Effacer les filtres

Using Optimizing Nonlinear Functions to find mutiple variations

1 vue (au cours des 30 derniers jours)
Lam Ha
Lam Ha le 8 Nov 2023
Commenté : Lam Ha le 9 Nov 2023
Hi everyone, I'm having some problems when using Optimization to find some variations.
I have the equation as following:
xdata=125:2:145;
ydata=[0.002 0.003 0.009 0.025 0.053 0.089 0.104 0.09 0.07 0.041 0.017];
y=@(x)(-1/(dev*sqrt(2*pi))*exp(-1/2*((xdata-mean)/dev).^2);
with dev a.k.a deviation and mean is two fixed parameters I have to find.
I have referenced the Optimizing Nonlinear Functions and Solve a Constrained Nonlinear Problem, Solver-Based in Matlab.
This is my code.
%%%Function code
function sse = sseval(n,xdata,ydata)
mean=n(1);
dev=n(2);
sse=ydata-1/(dev*sqrt(2*pi))*exp(-1/2*((xdata-mean)/dev).^2);
end
%%%Main code
clc;
clear all;
close all;
xdata=[125 127 129 131 133 135 137 139 141 143 145];
ydata=[0.002 0.003 0.009 0.025 0.053 0.089 0.104 0.09 0.07 0.041 0.017];
%%%%Find mean and deviation value
rng default %for reproducibility
type sseval
fun = @(n)sseval(n,xdata,ydata);
x0=rand(2,1);
bestn=fminsearch(fun,x0)
The result showed the error and cannot run. Can anyone show me what is the problem with this? Thank you so much in advanced.

Réponse acceptée

Torsten
Torsten le 8 Nov 2023
xdata=[125 127 129 131 133 135 137 139 141 143 145];
ydata=[0.002 0.003 0.009 0.025 0.053 0.089 0.104 0.09 0.07 0.041 0.017];
%%%%Find mean and deviation value
fun = @(n)sseval(n,xdata,ydata);
x0=[135,1];
bestn=fminsearch(fun,x0)
bestn = 1×2
137.4512 3.8956
xsim = xdata;
ysim = 1/(bestn(2)*sqrt(2*pi))*exp(-1/2*((xsim-bestn(1))/bestn(2)).^2);
hold on
plot(xsim,ysim)
plot(xdata,ydata,'o')
hold off
%%%Function code
function sse = sseval(n,xdata,ydata)
mean=n(1);
dev=n(2);
sse=ydata-1/(dev*sqrt(2*pi))*exp(-1/2*((xdata-mean)/dev).^2);
sse = sum(sse.^2);
end

Plus de réponses (1)

Matt J
Matt J le 8 Nov 2023
Modifié(e) : Matt J le 8 Nov 2023
There are also FEX downloads that can do gauss fitting for you, e.g.,
xdata=[125 127 129 131 133 135 137 139 141 143 145];
ydata=[0.002 0.003 0.009 0.025 0.053 0.089 0.104 0.09 0.07 0.041 0.017];
p=gaussfitn(xdata',ydata',[],{0,[],[]},{0,[],[]});
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.
[~,A,mu,sig2]=deal(p{:});
mu,
mu = 137.4548
dev=sqrt(sig2)
dev = 3.9507
x=linspace(min(xdata),max(xdata));
yfit=@(xx) A*exp(-1/2*((xx-mu)/dev).^2);
plot(xdata,ydata,'o',x,yfit(x))

Community Treasure Hunt

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

Start Hunting!

Translated by