How do I get Derivative of an inserted function ?

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

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

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

thank u dear Walter ,
and yes ,as u said I want to evaluate the derivative at x and this is my prob too :((
I want to use "feval()" as I mentioned in last comment bu I couldn't...
would u mind helping me ? :)
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,
thank u sooooo muchhhh :))))

Sign in to comment.

More Answers (0)

Categories

Tags

Asked:

on 12 Nov 2020

Commented:

on 12 Nov 2020

Community Treasure Hunt

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

Start Hunting!