A problem while using lsqnonlin

1 回表示 (過去 30 日間)
Caritas
Caritas 2020 年 6 月 10 日
編集済み: Caritas 2020 年 6 月 10 日
I want to find the parameter x using nonlinear solver lsqnonlin.
I think the two functions are the same, but ErrorFunc2 doesn't seem to work properly with the optimization process.
Can you tell me what the problem is?
d = linspace(0,3);
y = exp(-1.3*d) + 0.05*randn(size(d));
ErrorFunc = @(r)exp(-d*r)-y;
x0 = 4;
x = lsqnonlin(ErrorFunc,x0);
x2 = lsqnonlin(@ErrorFunc2,x0);
figure()
hold on
plot(d,y,'ko') % DATA
plot(d,exp(-x*d),'b-') % BEST FIT
plot(d,exp(-x2*d)) % BEST FIT
legend('Data','x1 fit', 'x2 fit')
xlabel('t')
ylabel('exp(-tx)')
function [error] = ErrorFunc2(x)
d = linspace(0,3);
y = exp(-1.3*d) + 0.05*randn(size(d));
error = exp(-d*x) -y;
end

採用された回答

Stephan
Stephan 2020 年 6 月 10 日
編集済み: Stephan 2020 年 6 月 10 日
Use the same random numbers for the same results:
rng('default')
d = linspace(0,3);
y = exp(-1.3*d) + 0.05*randn(size(d));
ErrorFunc = @(r)exp(-d*r)-y;
x0 = 4;
x = lsqnonlin(ErrorFunc,x0);
x2 = lsqnonlin(@ErrorFunc2,x0);
figure()
hold on
plot(d,y,'ko') % DATA
plot(d,exp(-x*d),'b-') % BEST FIT
plot(d,exp(-x2*d),'r--') % BEST FIT
legend('Data','x1 fit', 'x2 fit')
xlabel('t')
ylabel('exp(-tx)')
function [error] = ErrorFunc2(x)
rng('default')
d = linspace(0,3);
y = exp(-1.3*d) + 0.05*randn(size(d));
error = exp(-d*x) -y;
end
Another approach would be to generate random numbers only one time and use them as input to func2:
d = linspace(0,3);
y = exp(-1.3*d) + 0.05*randn(size(d));
ErrorFunc = @(r)exp(-d*r)-y;
x0 = 4;
x = lsqnonlin(ErrorFunc,x0);
x2 = lsqnonlin(@(x)ErrorFunc2(x,y),x0);
figure()
hold on
plot(d,y,'ko') % DATA
plot(d,exp(-x*d),'b-') % BEST FIT
plot(d,exp(-x2*d),'r--') % BEST FIT
legend('Data','x1 fit', 'x2 fit')
xlabel('t')
ylabel('exp(-tx)')
function [error] = ErrorFunc2(x,y)
d = linspace(0,3);
% y = exp(-1.3*d) + 0.05*randn(size(d));
error = exp(-d*x) -y;
end
  1 件のコメント
Caritas
Caritas 2020 年 6 月 10 日
編集済み: Caritas 2020 年 6 月 10 日
I thought the original expression exp(-1.3*x) would be the final result even if the random numbers (noise) were different, but it was wrong. Thank you for your answer!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLeast Squares についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by