error: eval: TRY must be a string

11 次查看(过去 30 天)
Deividas David
Deividas David 2021-11-22
编辑: DGM 2021-11-22
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 个评论
Geoff Hayes
Geoff Hayes 2021-11-22
@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.

请先登录,再进行评论。

回答(1 个)

DGM
DGM 2021-11-22
编辑:DGM 2021-11-22
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

类别

Help CenterFile Exchange 中查找有关 Language Fundamentals 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by