How do I use fminsearch to minimize the least-squares error for fitting data points to a function?

21 views (last 30 days)
I'm working on a problem where I have a function for the Gaussian normal distribution with 3 parameters and a variable, and I am trying to use fminsearch to fit the Gaussian function to a set of data points. The function I am trying to fit is as follows:
G = @(L,A,R,W) (A.*exp(-(L-R).^2 / W.^2))
where A, R, and W are the parameters that I'm trying to find using fminsearch. L is the variable. It's my understanding that, if my y data points are stored in sigma, and my corresponding y values are stored in lambda, then my error is as follows:
F_error = @(L,A,R,W) sum(abs((A.*exp(-(L-R).^2 / W.^2) - sigma).^2))
Therefore, I would think that I should be able to minimize this error and find what A, R and W with this line of code:
[X,Y,Z] = fminsearch(@(lambda) F_error(lambda,A,R,W),[2;500;sqrt(140)]);
with my initial guesses for A, R, and W being 2, 500, and sqrt(140), respectively.
However, I get an error saying that matrix dimensions must agree for subtraction. At this point, I'm not entirely sure what is going wrong or if I'm even taking the correct approach. I'd really appreciate any pointers to get me going in the right direction.
Also, for completeness, my data points are as follows:
lambda = (400:10:570)';
sigma = [.02;.1;.05;.2;.4;1;1.2;1.4;1.8;
2.2;2.1;1.7;1.5;1.1;.8;.3;.01;.2;];

Accepted Answer

Matt J
Matt J on 22 May 2013
Edited: Matt J on 22 May 2013
ARW = fminsearch(@(z) F_error(lambda,z(1),z(2),z(3)),[2;500;sqrt(140)]);
A=ARW(1);
R=ARW(2);
W=ARW(3);

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!