How do I get Derivative of an inserted function ?

4 views (last 30 days)
I want user insert the function and the program get Derivative of it by using the given code but it wouldn't work
and show me this message :
Undefined function 'diff' for input arguments of type 'inline'.
Error in Untitled (line 8)
m=diff(f)
.........................
my code :
clc
clear
str = input('Give an equation in x: ','s') ;
x = input('Type in a value of x: ') ;
f = inline(str,'x') ;
y = feval(f,x) ;
m=diff(f)
disp(['"' str '", for x = ' num2str(x) ', equals ' num2str(y)]) ;
  1 Comment
amir
amir on 12 Nov 2020
I find out the answer but now I have another question , how do I use inserted value for the derivative of func??
error:
Error using feval
Function to evaluate must be represented as a string scalar, character vector, or function_handle object.
Error in Untitled (line 9)
n=feval(df,2)
----------------------------------------------------
clc
clear
str = input('Give an equation in x: ','s') ;
x = input('Type in a value of x: ') ;
f = inline(str,'x') ;
y = feval(f,x) ;
syms x
df = diff(f(x),x)
n=feval(df,2)

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 12 Nov 2020
str = input('Give an equation in x: ','s') ;
x = input('Type in a value of x: ') ;
f = str2sym(str);
y = subs(f, sym('x'), x);
m = diff(f);
disp(['"' str '", for x = ' num2str(x) ', equals ' char(y)]) ;
Notice that you take the derivative but you do not display the derivative or calculate anything with it. I suspect that what you want to do is evaluate the derivative at x, not evaluate the function at x.
  3 Comments
Walter Roberson
Walter Roberson on 12 Nov 2020
str = input('Give an equation in x: ','s') ;
x = input('Type in a value of x: ') ;
f = str2sym(str);
m = diff(f);
y = subs(m, sym('x'), x);
disp(['"' str '", for x = ' num2str(x) ', equals ' char(y)]) ;
If you must use feval for some reason, then:
str = input('Give an equation in x: ','s') ;
x = input('Type in a value of x: ') ;
f(sym('x')) = str2sym(str);
m = diff(f);
y = feval(m, x);
disp(['"' str '", for x = ' num2str(x) ', equals ' char(y)]) ;
This adds useless overhead for no purpose,

Sign in to comment.

More Answers (0)

Categories

Find more on Search Path in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!