error: eval: TRY must be a string

7 vues (au cours des 30 derniers jours)
Deividas David
Deividas David le 22 Nov 2021
Modifié(e) : DGM le 22 Nov 2021
Hey guys, I'm trying to find zero in selected interval from a function graphic but all it gives me is an aerror that TRY must be a string.
The script is :
f = @(x) 0.1*x - sin(2 * x) + 0.25;
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
fgraf is:
function [k, d] = fgraf (fun, a, b)
dx = (b - a) / 100; % x step
x1 = a : dx : b;
y = x1;
[m, n] = size(x1);
for k = 1 : n % cycle begins
x = x1(k);
y(k) = eval(fun); % function calculation
end % cycle stops
plot(x1, y); % forming graph
grid on; xlabel('x');
ylabel(fun);
title('Tiriamos funkcijos grafikas');
[k, ky] = ginput(1);
[d, dy] = ginput(1);
end
  1 commentaire
Geoff Hayes
Geoff Hayes le 22 Nov 2021
@Deividas David - I don't understand this line of code (which may or may not be the source of the error)
y(k) = eval(fun);
What are you trying to evaluate? Can't you just do
for k = 1 : n % cycle begins
x = x1(k);
y(k) = fun(x); % function calculation
end
instead? Since fun is your function handle that requires an input.

Connectez-vous pour commenter.

Réponses (1)

DGM
DGM le 22 Nov 2021
Modifié(e) : DGM le 22 Nov 2021
Why won't something like this work?
f = @(x) 0.1*x - sin(2 * x) + 0.25;
for i = 1:3
[a, b] = fgraf(f, -3, 3);
z = fzero(@(x) 0.1*x - sin(2*x) + 0.25, [a, b]); % don't overwrite f
fprintf('Zero found in the interval: %s\n',mat2str([a, b],5))
fprintf('zero is at is %.4f \n\n',z) % don't use ans
end
function [k, d] = fgraf(fun, a, b)
x = linspace(a,b,100);
y = fun(x); % no loops, no eval
plot(x, y);
grid on;
xlabel('x');
ylabel(char(fun)); % fixed
title('Tiriamos funkcijos grafikas');
[k,~] = ginput(1);
[d,~] = ginput(1);
end

Catégories

En savoir plus sur Language Fundamentals dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by