您已使此代码绘制函数。
我需要用红色X标记x = 0和图表中蓝色波浪线之间的所有交叉点。
我做了一些尝试,但在绘图功能中使用'-xr',但是它会在交叉点之外放置X标记。
任何人都知道怎么做。非常感谢。
代码:
% entrada
a = input('Introduza o valor de a: ');
% ficheiro fonte para a função
raizes;
% chamada à função
x = 0:.1:50;
or = x;
or(:) = 0;
h = @(x) cos(x);
g = @(x) exp(a*x)-1;
f = @(x) h(x) - g(x);
zeros = fzero(f,0);
plot(x,f(x));
hold on
plot(zeros,f(zeros),'-xr')
hold off
图表(它只标记一个零,我需要所有过零点):
答案 0 :(得分:2)
如上面的评论所述,您需要在绘制函数之前查找函数的零。你可以用数学方法做到这一点(在这种情况下设置为f(x) = g(x)
并求解x),或者你可以用fsolve
之类的方法进行分析。
如果您阅读fsolve
的文档,您会看到如果传递标量,它会搜索最接近提供的x0
的零,如果传递了间隔,则会搜索第一个零。我们为快速尝试解决方案而做的是将x
值作为初始猜测传递给fsolve
并过滤掉唯一值。
% Set up sample data
a = .05;
x = 0:.1:50;
% Set up equations
h = @(x) cos(x);
g = @(x) exp(a*x)-1;
f = @(x) h(x) - g(x);
% Find zeros of f(x)
crossingpoints = zeros(length(x), 1); % Initialize array
for ii = 1:length(x) % Use x data points as guesses for fzero
try
crossingpoints(ii) = fzero(f, x(ii)); % Find zero closest to guess
end
end
crossingpoints(crossingpoints < 0) = []; % Throw out zeros where x < 0
% Find unique zeros
tol = 10^-8;
crossingpoints = sort(crossingpoints(:)); % Sort data for easier diff
temp = false(size(crossingpoints)); % Initialize testing array
% Find where the difference between 'zeros' is less than or equal to the
% tolerance and throw them out
temp(1:end-1) = abs(diff(crossingpoints)) <= tol;
crossingpoints(temp) = [];
% Sometimes catches beginning of the data set, filter it out if this happens
if abs(f(crossingpoints(1))) >= (0 + tol)
crossingpoints(1) = [];
end
% Plot data
plot(x, f(x))
hold on
plot(crossingpoints, f(crossingpoints), 'rx')
hold off
grid on
axis([0 20 -2 2]);
这给了我们以下内容:
请注意,由于errors arising from floating point arithmetic,我们必须使用容差来过滤我们的零,而不是使用像unique
这样的函数。