Problem using function with fminsearch

10 views (last 30 days)
Jonathan on 20 Jan 2014
Edited: Amit on 20 Jan 2014
I have a set of data that I want to perform a fit to (data X and Y). I want to fit this data to a function Yfit = A / (1+(X/B)), where A and B are coefficients I want to find by minimising the sum of the squared residuals using fminsearch .
Here’s what I am trying at the moment: First, in a separate .m file I define the Yfit function:
function[res] = Yfit_func(A,B,X)
Yfit = A/(1+(X/B));
res = sum((Y-Yfit).^2);
As I understand, that defines a function called “Yfit_func”, with an output called “res”, and inputs “A”, “B” and “X”. “res” is the residuals term to be minimised to find A and B.
In the main .m file I call the fitting function using:
Coefficients = fminsearch(@Yfit_func, guess,[], Y, X);
My understanding of that line is that fminsearch calls the function "Yfit_func", uses the values contained in "guess" as starting points for finding the values of A and B that minimise "res" when fitting the function in "Yfit_func" to the data contained in X and Y.
The error I get is: “Error using / Matrix dimensions must agree. Error in Yfit_func (line 2) Yfit = A/(1+(X/B));”
Not sure what's going wrong here, any help would be appreciated. Thanks.

Accepted Answer

Amit on 20 Jan 2014
Edited: Amit on 20 Jan 2014
Use your function like this
function res = Yfit_func(A,Y,X)
Yfit = A(1)./(1+(X/A(2)));
res = sum((Y-Yfit).^2);
and run fminsearch like this:
guess = rand(2,1); % your starting point, You can change this
Coefficients = fminsearch(@(A) Yfit_func(A,Y,X), guess);
fminsearch does not takes input like you have used.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!