My first fzero calculates just fine but the one after gives me an error eval: TRY must be a string
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (1)
Sulaymon Eshkabilov
am 21 Nov. 2021
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 Kommentar
Walter Roberson
am 21 Nov. 2021
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
Produces a value but the value is assigned to a variable, ans is not assigned to
whos
5
whos, ans
expression that produces a value, value was not assigned to a variable, ans is assigned to
x+7;
whos, ans
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.
Siehe auch
Kategorien
Mehr zu Testing Frameworks finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!