Imported variable is not transferred to fzero- function

function y = fzero_optimset(~,~)
x = -5:.01:5;
disp('Please enter a value for variable a!')
a = input('a = ');
y = 1./(1+x.^2) + a * x - 1/2;
plot(x,y);
grid on;
hold on;
x0 = fzero('1./(1+x.^2) + a * x - 1/2',-1,optimset,.1);
plot(x0,0,'x');
end

1 件のコメント

Matt J
Matt J 2021 年 9 月 2 日
@Florian Roeder's comment moved here
In line 3 of my code, user is prompted to enter a value for variable a.
When I run the code, function "y=1./(1+x.^2)+a*x-1/2" is evaluated correctly. Figure is correct as well.
When function reaches line "x0 = fzero('1./(1+x.^2) + a * x - 1/2',-1,optimset,.1);" , MATLAB shows following error message:
FZERO cannot continue because user-supplied expression ==>
1./(1+x.^2) + a * x - 1/2 failed with the error below.
Error in inline expression ==> 1./(1+x.^2) + a * x - 1/2
Undefined function or variable 'a'.
Error in fzero_optimset (line 20)
x0 = fzero('1./(1+x.^2) + a * x - 1/2',-1,optimset,.1);
How can I handle this problem? I don´t know how to change the code.

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

 採用された回答

Matt J
Matt J 2021 年 9 月 2 日
編集済み: Matt J 2021 年 9 月 2 日

0 投票

Use more modern techniques for specifying the function and passing fixed parameters to it, e.g.,
a=1;
x0 = fzero(@(x) 1./(1+x.^2) + a * x - 1/2,-1)
x0 = -0.3761

1 件のコメント

Florian Roeder
Florian Roeder 2021 年 9 月 3 日
Thanks a lot. Is there any possibility to get it running in an editor- file? The code above was copied from an editor- file generating the error message shown above. When I type in modified code (your solution), everything is running properly. Copying the same code in the editor- file shows the error message again. Figure is drawn correctly each time, fzero- command generates the error.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeOptimization についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by