Problem using function with fminsearch

4 vues (au cours des 30 derniers jours)
Jonathan
Jonathan le 20 Jan 2014
Modifié(e) : Amit le 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);
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.

Réponse acceptée

Amit
Amit le 20 Jan 2014
Modifié(e) : Amit le 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);
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.

Plus de réponses (0)

Catégories

En savoir plus sur Nonlinear Optimization dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by