2015-11-16 31 views
0

您已經使此代碼繪製一個函數。Octave - 用紅色的X標記標記過零點

我需要用紅色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 

圖(它不僅標誌着一個零,我需要所有的過零點):

enter image description here

+0

您必須首先以數學方式找到交叉點。 – excaza

+0

數學?有沒有一個公式呢? –

+1

是嗎?設置'f(x)= 0',解決'x' ... – excaza

回答

2

正如評論上面提到的,你在繪製它們之前,需要查找函數的零點。你可以用數學方法做到這一點(在這種情況下,設置f(x) = g(x)並解決x),或者你可以用fsolve這樣的分析方法做到這一點。

如果您閱讀fsolve的文檔,您將看到如果傳遞標量或者如果傳遞時間間隔,則會搜索與提供的x0最接近的零。我們可以做的快速嘗試解決方案是將我們的x值作爲初始猜測並過濾出唯一值。

% 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]); 

這給了我們如下:

yay

注意,由於errors arising from floating point arithmetic我們必須利用公差來過濾零,而不是利用函數像unique

+0

非常感謝。偉大的一段代碼。但是它在測試時會出錯 - > error:script:A(I,J):行索引超出範圍;值501越界1 –

+0

錯誤位於 - > crossingpoints = zeros(length(x),1); –

+0

任何解決方案?我無法解決錯誤。它只在x值=只有一個標量值時消失。間隔時間總是錯誤的。 –