フィルターのクリア

How to create a vector and populate it with the first 10 roots using this Newtons method code?

1 回表示 (過去 30 日間)
I've created this code to calculate roots by using Newtons Method. However I only need the first 10 roots that I find with this code. I think I have to create a 10x1 matrix and populate it with the results that are not repeated. I have no idea how to do that... Any ideas? Thanks!!
syms f(x) x
f(x) = x*tan(x)-0.1; %Function
g = diff(f);
for e=1:100 %Trying different initial guesses to get all the roots
x(1)=e ;%initial guess
for i=1:1000 %it should be stopped when tolerance is reached
x(i+1) = x(i) - f(x(i))/g(x(i));%Newtons Method
if( abs(f(x(i+1)))<0.001) % tolerance
disp(double(x(i+1))); %Display result
break;
end
end
end

採用された回答

Alan Stevens
Alan Stevens 2020 年 9 月 11 日
Something more like this perhaps (no need for symbolic maths).
f = @(x) x.*tan(x)-0.1; %Function
g = @(x) x.*tan(x).^2 + tan(x) + x;
tol = 0.001;
X = zeros(10,1); % Space for 10 roots
for i = 1:10 % loop for each root in turn
err = 1;
x = i*pi; % initial guess
while err>tol
xold = x;
x = x - f(x)/g(x);%Newtons Method
err = abs(x - xold);
end
X(i) = x;
end
fprintf('Roots\n')
fprintf('%8.4f \n',X)
Notice the way anonymous functions are defined.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by