Help with a vector

6 ビュー (過去 30 日間)
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 9 月 30 日
コメント済み: Lavorizia Vaughn 2021 年 9 月 30 日
Hello. I have come up with the following code:
function p = findmanyzeros(f, a, b, n, tol)
x = a + (b-a)*(0:n)/n;
fx = f(x);
p = [];
for i = 1:n
if sign(fx(i)) ~= sign(fx(i+1))
p(end+1) = findzero(f, x(i), x(i+1), tol);
end
end
My instructions were to Implement a MATLAB function findmanyzeros 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, k=0,...,n, between a and b
2. For k = 1,...,n, if f(xk) and f(xk1) have different signs, compute a zero using findzero
3. The output vector p should contain all the computed zeros
  5 件のコメント
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 9 月 30 日
>> f= @(x) cos(x)-x;
>> findzeros(f, 0, 1, 10, 10^-4)
Unrecognized function or variable 'fx'.
Error in findzeros (line 6)
if sign(fx(i)) ~= sign(fx(i+1))
>>
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 9 月 30 日
編集済み: Cris LaPierre 2021 年 9 月 30 日
f= @(x) cos(x)-x
f = function_handle with value:
@(x)cos(x)-x
findzeros(f, 0, 1, 10, 10^-4)
Unrecognized function or variable 'fx'.

Error in solution>findzeros (line 7)
if sign(fx(i)) ~= sign(fx(i+1))
function p = findzeros(f,a,b,n,tol)
x=a+(b-a)*(0:n)/n;
p=[];
for i = 1:n
if sign(fx(i)) ~= sign(fx(i+1))
p(end+1) = findzero(f, x(i), x(i+1), tol);
end
end
end

サインインしてコメントする。

採用された回答

Cris LaPierre
Cris LaPierre 2021 年 9 月 30 日
編集済み: Cris LaPierre 2021 年 9 月 30 日
You have not defined a variable fx inside your findzeros function. Do you mean to use f?
You have created a recursive function but you have not defined an exit criteria. Since sign(f(i) always is the same as sign(f(i+1)), p is never assigned a value, and your result is an empty vector.
f= @(x) cos(x)-x;
f(1:10)
ans = 1×10
-0.4597 -2.4161 -3.9900 -4.6536 -4.7163 -5.0398 -6.2461 -8.1455 -9.9111 -10.8391
  1 件のコメント
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 9 月 30 日
thank you ive figured it out.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics and Optimization についてさらに検索

タグ

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by