Clear Filters
Clear Filters

Definition of the error function in lsqnonlin

2 views (last 30 days)
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!

Accepted Answer

Torsten
Torsten on 12 May 2023
Edited: Torsten on 12 May 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 Comments
Torsten
Torsten on 12 May 2023
Edited: Torsten on 12 May 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.
Raffaele
Raffaele on 12 May 2023
Yes, the problem was that in the error function f and experimental_data might have diffeent size. Now I have changed the code in order to assure that they have the same size and I have no errors.
Thank you very much for the help!!

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!