My first fzero calculates just fine but the one after gives me an error eval: TRY must be a string

조회 수: 2(최근 30일)
Deividas David
Deividas David 2021년 11월 21일
댓글: Walter Roberson 2021년 11월 21일
Hello guys, so I've been trying to find zero in interval for a function using fzero. I get my first answer right but when it tries to go for other ones it just gives me an error eval: TRY must be a string
for i = 1:3
[a, b] = fgraf(f, -3, 3);
f = fzero(@(x) 0.1*x - sin(2*x) + 0.25, [a, b]);
disp(strcat("Zero found in the interval: ", num2str([a, b])));
disp(ans);
disp("");
end
x0 = a; dx = eps;
atlikta = 0;
while ~atlikta
x = x0;
f0 = eval(f);
x = x + dx;
fd = eval(f);
df = (fd - f0) / dx;
x1 = x0 - f0 / df;
if abs(x1 - x0) < eps
atlikta = 1;
else
x0 = x1;
end
spr = x1;
end
Unrecognized function or variable 'f'.

답변(1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 11월 21일
There are a few inconsistencies in your codes, i.e.,
f is a fcn not defined as a fcn handle or fcn file. What is fgraf() fcn?
The variable "ans" is not defined.
Just presuming that the problem exrcise and interval, the following can be used
F=@(x) 0.1*x - sin(2*x) + 0.25;
a=-3; b=3;
f = fzero(F, [a, b]);
disp(strcat("Zero found in the interval: ", num2str([a, b])));
disp(f);
disp("");
x0 = a; dx = eps;
atlikta = 0;
while ~atlikta
x = x0;
f0 = F(x);
x = x + dx;
fd = F(x);
df = (fd - f0) / dx;
x1 = x0 - f0 / df;
if abs(x1 - x0) < eps
atlikta = 1;
else
x0 = x1;
end
spr = x1;
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 11월 21일
ans is a special name in MATLAB. Each time there is a computation that would normally return a value, and the value is not being assigned to a variable, then MATLAB assigns the value to ans . For example,
x = 3
x = 3
Produces a value but the value is assigned to a variable, ans is not assigned to
whos
Name Size Bytes Class Attributes x 1x1 8 double
5
ans = 5
whos, ans
Name Size Bytes Class Attributes ans 1x1 8 double x 1x1 8 double
ans = 5
expression that produces a value, value was not assigned to a variable, ans is assigned to
x+7;
whos, ans
Name Size Bytes Class Attributes ans 1x1 8 double x 1x1 8 double
ans = 10
Expression, output was supressed, but ans was assigned to.
Notice in all of these that even though I called whos, ans did not become the potential output of whos (whos can be called as a function.) Some functions check to see whether any outputs are requested, and if not then they do not assign to any output variable; when that happens, ans is not changed.

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by