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 Center および File ExchangeLanguage Fundamentals についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by