Problem using function with fminsearch

9 次查看(过去 30 天)
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);
end
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.

采纳的回答

Amit
Amit 2014-1-20
编辑:Amit 2014-1-20
Use your function like this
function res = Yfit_func(A,Y,X)
Yfit = A(1)./(1+(X/A(2)));
res = sum((Y-Yfit).^2);
end
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Polynomials 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by