# Error in using diff for derivative

4 ビュー (過去 30 日間)
Anantha Krishna B 2022 年 1 月 18 日
コメント済み: Torsten 2022 年 1 月 19 日
Hello
I am writing a function for calculating a root of a function using Newton's Method. In this i need to calculate value of derivative of the function. So I used diff but I am getting an error. I am thinking that the error is because diff only acts on symbolic functions and this somehow causes error. Is there any alternative way?
Below is my code
function [root] = Newton_rap_fun(a, error, f)
% function for newton's method
% a is the initial approximation, error is the error tolerance given by
% user
% f is the given function
while (true)
if (diff(f(a)) ~= 0)
b = a - f(a)/diff(f(a));
if (abs(b-a) <= error)
root = b;
break
end
else
root = a;
end
end
##### 3 件のコメント表示非表示 2 件の古いコメント
Torsten 2022 年 1 月 19 日
Numerical difference approximations exist also for derivatives of order n>1:
Or use symbolic maths and MATLAB's diff-command.

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

### 回答 (1 件)

VBBV 2022 年 1 月 19 日
t = f(a);
while (true)
if (abs(b-a) <= error)
root = b;
break
end
else
root = a;
end
end
check with this
##### 1 件のコメント表示非表示 なし
Torsten 2022 年 1 月 19 日
f(a) is a scalar. "gradient" makes no sense in this case.

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

R2021b

### Community Treasure Hunt

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

Start Hunting!