Definition of the error function in lsqnonlin
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Raffaele
el 12 de Mayo de 2023
Comentada: Raffaele
el 12 de Mayo de 2023
Hello, I'm trying to fit experimental data with a function let's say f(x) which is quite complicated and I cannot use the curve fitting tool. The problem is that to define the error function I have to do some operation with this f(x) function, which are not allowed since it is an anonymous function. To explain better I give an example with a simple f(x) function:
x = 0:1/10000:10
f = @(p) x*p(1) + exp(x*p(2));
Now, to define the error function with respect to the experimental data I need to do some operation on this function f, for example:
% Preliminary operations
f = f + abs(min(f));
f = f./f(1) * 3;
idx_start = dsearchn(f, 5);
f = f(idx_start:end);
And finally the error function:
err = f - experimental_data;
So I can use lsqnonlin:
p0 = [1 2];
p = lsqnonlin(err, p0);
Now the problem is that until the initial values p(1) and p(2) are defined, matlab does not allow you to do all those preliminary operations necessary to define the error function since f is an anonymous function (with symbolic p).
Is there a way then to define the error function only after the initial conditions have been chosen? Or is there a way to do those operations directly on f even if it's an anonymous function?
I hope I was clear, have a nice day and thank you!
0 comentarios
Respuesta aceptada
Torsten
el 12 de Mayo de 2023
Editada: Torsten
el 12 de Mayo de 2023
Use a function instead of a function handle.
p0 = [1 2];
x = 0:1/10000:10
p = lsqnonlin(@(p)fun(p,x), p0);
function err = fun(p,x)
...
err = ...;
end
3 comentarios
Torsten
el 12 de Mayo de 2023
Editada: Torsten
el 12 de Mayo de 2023
I'm surprised that an error message appears after lsqnonlin seems to have finished.
My guess is that the number of elements of the vector "err" mustn't change during a computation with lsqnonlin.
So I'd choose the length of "err" as numel(x) and return zeros for the elements you don't want to consider after a call to your function.
If the problem persists, we need to be able to reproduce the error with adequate code from your side.
Más respuestas (0)
Ver también
Categorías
Más información sobre Interpolation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!