error: eval: TRY must be a string

조회 수: 10(최근 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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by