MATLAB Answers

How do I get my function to form the derivative for Newton-Method

4 ビュー (過去 30 日間)
Marcus Schlitter
Marcus Schlitter 2019 年 11 月 27 日
Commented: Marcus Schlitter 2019 年 11 月 28 日
Hey everyone,
I'm new here so please bear with me. I want to write a Newton-Function to practise in Matlab and find zero points. However, it works fine if I give the derivative. But I want it to form the derivative itself, since I am prone of making dumb mistakes in exams. Here is my code (I hope I did insert it correctly):
function [x] = Newton(f,x,m)
syms x
fderiv = diff(f,x); %I'm trying to tell him to define the derivative of f as fderiv to use it afterwards
for i = 1:m
x(i+1) = x(i) - f(x(i))/fderiv(x(i)) ; % The newton formula x(n) = x(n-1) - f(x(n-1))/f'(x(n-1)
if abs(x(i+1)-x(i)) < 2*10^(-5) %criteria to abort nonsense iteration
break
end
end
disp(x(end))
end
So I give him f , x (as a starting value) and m as iteration steps:
f =@ (x) 2*x^2-5; x = 1.5 ; m = 15 ;
I get following error:
>> Newton(f,x,m)
Error using sym/subsindex (line 836)
Invalid indexing or function definition. Indexing must follow MATLAB
indexing. Function arguments must be symbolic variables, and function
body must be sym expression.
Error in sym/subsref (line 881)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in Newton (line 20)
x(i+1) = x(i) - f(x(i))/fderiv(x(i)) ;
Maybe somebody knows what I could do, I'd really appreciate it. Have a great day,
Lg,
Marcus

  0 件のコメント

サインイン to comment.

採用された回答

David Hill
David Hill 2019 年 11 月 27 日
function [b] = Newton(f,x,m)
b=x;
syms x
fderiv = diff(f,x);
for i = 1:m
b(i+1) = b(i) - f(b(i))/subs(fderiv,b(i)) ;
if abs(b(i+1)-b(i)) < 2*10^(-5)
break
end
end
disp(b(end))
end

  1 件のコメント

Marcus Schlitter
Marcus Schlitter 2019 年 11 月 28 日
It worked :) Thank you so much!

サインイン to comment.

More Answers (1)

Steven Lord
Steven Lord 2019 年 11 月 27 日
The diff function doesn't know how to operate on arbitrary function handles, including anonymous function handles. For functions than can be evaluted for symbolic variables, like the one you've specified, you could evaluate it and call diff on the resulting symbolic expression.
f =@ (x) 2*x^2-5; x = 1.5 ; m = 15 ;
syms x
fs = f(x)
dfs = diff(fs, x)

  1 件のコメント

Marcus Schlitter
Marcus Schlitter 2019 年 11 月 28 日
Ah looks like I really need to learn more about diff :D Thank you very much!

サインイン to comment.

サインイン してこの質問に回答します。


Translated by