Creating a Function That Finds Zeros
5 次查看(过去 30 天)
显示 更早的评论
Hello,
I am trying to make a function of the form
function p = findmanyzeros(f, a, b, n, tol)
Which finds zeros in the interval [a, b] using the following strategy:
1. Compute n+1 equidistant points xk for k=0,...,n, between a and b
2. For k = 1,...,n, if f(xk) and f(xk−1) have different signs, compute a zero using findzero
3. The output vector p should contain all the computed zeros
I believe the code i have (which is below) is terribly wrong, but its my best shot. I would appreciate some help. thanks.
function p = findmanyzeros(f, a, b, n)
x = linspace(a,b,n+1);
for k = 1:n
if f(x(k))*f(x(k+1))<0
p(k)=findzero(f);
break;
end
11 个评论
Walter Roberson
2021-9-30
You posted very similar code in another Question. In that other place, you noted that it warned about p = [p,z] and it gave you an error about findzero not being found. Is that the same issues as here?
MATLAB does not supply any findzero() function, so you would have to supply your own.
Hint: compare
N = 20;
x = 1:N;
z = [];
for K = 1 : N
if isprime(K); z = [z, K]; end
end
z
to
N = 20;
x = 1:N;
P = false(1,N);
for K = 1 : N
if isprime(K); P(K) = true; end
end
x(P)
Notice that the second of these does not grow any arrays dynamically.
回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!