您可以沿着数组继续t
并查找值更改符号的点。这将表明零的存在。
实际上,MATLAB 的fzero
函数使用了类似的方法。您说您没有使用它是因为您需要一个数组,而不是匿名函数,但是您可以使用简单的线性插值将数组转换为匿名函数,如下所示:
func = @(k) interp1(x,t,k); % value of t(x) interpolated at x=k
fzero(func,initial_value);
编辑:只是为了澄清我的意思。如果你有一个数组t
并且你想找到它的零点......
f = 5; % frequency of wave in Hz
x = 0:0.01:1; % time index
t = cos( 2*pi*f*x ); % cosine wave of frequency f
zeroList = []; % start with an empty list of zeros
for i = 2:length(t) % loop through the array t
current_t = t(i); % current value of t
previous_t = t(i-1); % previous value of t
if current_t == 0 % the case where the zero is exact
newZero = x(i);
zeroList = [zeroList,newZero];
elseif current_t*previous_t < 0 % a and b have opposite sign if a*b is -ve
% do a linear interpolation to find the zero (solve y=mx+b)
slope = (current_t-previous_t)/(x(i)-x(i-1));
newZero = x(i) - current_t/slope;
zeroList = [zeroList,newZero];
end
end
figure(1); hold on;
axis([ min(x) max(x) -(max(abs(t))) (max(abs(t))) ]);
plot(x,t,'b');
plot(x,zeros(length(x)),'k-.');
scatter(zeroList,zeros(size(zeroList)),'ro');
我得到的零是正确的:
