How do I get my function to form the derivative for Newton-Method
조회 수: 9 (최근 30일)
이전 댓글 표시
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
채택된 답변
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개)
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Calculus에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!