How to find the derivative of the function at some value of x?
Ältere Kommentare anzeigen
I am trying to write a code for the Newton-Raphson iteration method. So at first i created a function
function y=f1(x)
y=x^2-3*x+2;
Then in next M-file,i wrote
syms x;
x(1)=0;
i=1;
x(i);
z=f1(x(i))
But then I try to differentiate the function
df= eval((subs(diff(f1,x,x(i)),x,x(i))))
it shows error.
how do i solve the problem? I tried various ways but none of them worked. How do i call the function from previous M-file?
Akzeptierte Antwort
Weitere Antworten (2)
Karan Gill
am 5 Jul. 2017
Bearbeitet: Karan Gill
am 17 Okt. 2017
To differentiate a function and then find the value, use symbolic functions. For details, see https://www.mathworks.com/help/symbolic/create-symbolic-functions.html
>> syms f(x)
>> f(x) = x^2 -3*x + 2
f(x) =
x^2 - 3*x + 2
>> g = diff(f)
g(x) =
2*x - 3
>> g(2) % value at x = 2
ans =
1
>> xValues = [-10 5 88]
xValues =
-10 5 88
>> g(xValues)
ans =
[ -23, 7, 173]
3 Kommentare
Shanjul Shrivastava
am 10 Feb. 2020
U have made my life simple... :P
Sarah Johnson
am 12 Feb. 2020
This does not print out the values at g, when I plug it in it prints out the functions themselves
Walter Roberson
am 13 Feb. 2020
>> f(x) = x^2 -3*x + 2
f(x) =
x^2 - 3*x + 2
>> g = diff(f)
g(x) =
2*x - 3
>> g(7)
ans =
11
Works for me.
When I was glancing at your other recent post, it looked to me as if you have a different question: namely to determine the value of a constant in the formula such that the known boundary value was satisfied.
Hamza saeed khan
am 24 Nov. 2020
0 Stimmen
Undefined function or variable 'syms'.
Error in difff (line 2)
syms y(x)
1 Kommentar
Walter Roberson
am 24 Nov. 2020
If you get that answer, then you do not have the Symbolic Toolbox installed and licensed.
There are some third-party symbolic packages that can be used with MATLAB with varying degrees of difficulty. Some of them are commercial; some of them are free (such as symbolic python).
If you do not have a symbolic software package of some kind, then derivatives can be calculated for some restricted cases such as polynomials or piecewise polynomials (including cubic spline); beyond that you start having to do numeric approximations of derivatives.
Kategorien
Mehr zu Number Theory finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!