I am new to matlab and want to calculate something like f(x)/f'(x). I want the user to input the function f(x), the parameter x and a value of x (suppose 5,so that I can evaluate f(5)/f'(5)) .Please suggest what I should do.
Asked
Active
Viewed 75 times
-1
-
Do you have symbolic toolbox? There are two very different approaches depending on whether or not you use it. – Ben Voigt Feb 12 '17 at 20:23
-
Be sure to let me know if the answer I have provided works for you. – codingEnthusiast Feb 12 '17 at 21:03
-
@ Ben Voigt :I searched around and found a method to input a function,its parameter and the value but NOT the differentiation. However, I would be grateful I you could tell me about the two approaches. – Mathematica Noob Feb 12 '17 at 21:04
2 Answers
0
One approach is to use symbolic variables
function [ val ] = func( fun, num )
symfun = sym(fun);
dsymfun = diff(symfun);
y = symfun/dsymfun;
val = subs(y, num);
end
and then call it
e.g.
value = func('x^2', 5)
value =
5/2
Otherwise, you can provide your input as a symbolic variable:
function [ val ] = func( fun, num )
dfun = diff(fun);
y = fun/dfun;
val = subs(y, num);
end
and then write
syms x;
func(x^2, 5)

codingEnthusiast
- 3,800
- 2
- 25
- 37
-
Thanks @ nikaltipar The program is correct. But I need to input the function f as well as the parameter. – Mathematica Noob Feb 12 '17 at 21:07
0
You can do this using polyder
and polyval
as follows:
f = input('Enter f(x): '); %e.g; Enter [1 3 4] if f(x)= x^2 + 3*x + 4
df = polyder(f); %f'(x)
x= input('Enter x: '); %Enter the value of 'x' e.g 5
fx_dfx= polyval(f,x)/ polyval(df,x) %f(x)/f'(x)
If you have Symbolic Math Toolbox, you can also do this using:
syms x; %Creating a symbolic variable x
f = input('Enter f(x): '); %Enter f(x) e.g: x^2 + 3*x + 4
f(x)= f; %Converting sym to symfun
df(x) = diff(f) %f'(x)
x_val= input('Enter x: '); %Enter the value of 'x' e.g 5
fx_dfx = double(f(x_val)/df(x_val)) %f(x)/f'(x)

Sardar Usama
- 19,536
- 9
- 36
- 58