How to fit a defined function?

13 visualizaciones (últimos 30 días)
Sourabh Jain
Sourabh Jain el 10 de Nov. de 2022
Comentada: Star Strider el 10 de Nov. de 2022

I want to fit a custom function to my experimental data. For simplicity, I have some arbitary x & y values and a very simple linear function. I write the following code:

clear all;

x = [1 2 3 4 5]'; % x data
y = [.8 4 10 18 23]'; % y data

Y = lsqcurvefit(fun,1,x,y) % fitting function 'fun' defined below to find parameter 'a'

function y = fun(a,x)
y = a*x; % just a simple function for example, in actual problem, it is a long complicated function with various parameters
end

I get the following error: 'Not enough input arguements.'

I know this particular simple function can be defined as anonymous function and be fitted but I don't it that way.

Respuesta aceptada

Star Strider
Star Strider el 10 de Nov. de 2022
The ‘fun’ function must be presented to lsqcurvefit as a function handle using the ‘@’ operator —
x = [1 2 3 4 5]'; % x data
y = [.8 4 10 18 23]'; % y data
Y = lsqcurvefit(@fun,1,x,y) % fitting function 'fun' defined below to find parameter 'a'
Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
Y = 4.1055
function y = fun(a,x)
y = a*x; % just a simple function for example, in actual problem, it is a long complicated function with various parameters
end
See What Is a Function Handle? for details.
.
  2 comentarios
Sourabh Jain
Sourabh Jain el 10 de Nov. de 2022
Thank you Star Strider for your answer. It solved my problem.
Star Strider
Star Strider el 10 de Nov. de 2022
As always, my pleasure!

Iniciar sesión para comentar.

Más respuestas (2)

VBBV
VBBV el 10 de Nov. de 2022
Editada: VBBV el 10 de Nov. de 2022
To define a and then call in function
  2 comentarios
VBBV
VBBV el 10 de Nov. de 2022
Then use @
Y = lsqcurvefit(@fun,1,x,y)
Sourabh Jain
Sourabh Jain el 10 de Nov. de 2022
Thank you for your respone, it helped me.

Iniciar sesión para comentar.


Torsten
Torsten el 10 de Nov. de 2022
Editada: Torsten el 10 de Nov. de 2022
A simpler way for this problem, but I guess your "real" model is more complicated:
x = [1 2 3 4 5]'; % x data
y = [.8 4 10 18 23]'; % y data
a = x\y
a = 4.1055
  1 comentario
Sourabh Jain
Sourabh Jain el 10 de Nov. de 2022
Thank you Torsten for this intelligent answer, I really like your perspective.
Yes, my actual problem is not so simple, it is a transfer matrix model.

Iniciar sesión para comentar.

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by