Definition of the error function in lsqnonlin
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Interpolation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!