繁体   English   中英

八度-用红色X标记标记零交叉

[英]Octave - Mark zero crossings with an red X mark

嗨,您做了这段代码来绘制函数。

我需要在图中用红色X标记x = 0和蓝色波浪线之间的所有交叉点。

我进行了一些尝试,但在plot函数中使用了“ -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

图(它只标记一个零,我需要所有零交叉):

在此处输入图片说明

如以上注释中所述,您需要先查找函数的零点,然后才能对其进行绘制。 您可以用数学方法做到这一点(在这种情况下,设置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]);

这给我们以下内容:

好极了

请注意,由于浮点算法产生的错误,我们必须利用公差来过滤零点,而不是利用诸如unique的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM