error: eval: TRY must be a string

7 views (last 30 days)
Deividas David
Deividas David on 22 Nov 2021
Edited: DGM on 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 Comment
Geoff Hayes
Geoff Hayes on 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.

Sign in to comment.

Answers (1)

DGM
DGM on 22 Nov 2021
Edited: DGM on 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

Categories

Find more on Graphics Performance in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!