필터 지우기
필터 지우기

Definition of the error function in lsqnonlin

조회 수: 2 (최근 30일)
Raffaele
Raffaele 2023년 5월 12일
댓글: Raffaele 2023년 5월 12일
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!

채택된 답변

Torsten
Torsten 2023년 5월 12일
편집: Torsten 2023년 5월 12일
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
Torsten
Torsten 2023년 5월 12일
편집: Torsten 2023년 5월 12일
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 2023년 5월 12일
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!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interpolation에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by