0

As a programming exercise I have written a Matlab function which finds the derivative of a function using the finite difference method. In a script I have called the function and wish to check it using the built-in functions, except I am having trouble implementing this.

In order to get a check I use diff(eqn) to get the differentiated equation, however I am not sure how to use this equation to then solve for a particular value, eg. x = 2.

Here is my code:

syms x

eqn= cos(x);

%set value for the derivative to be evaluated at
x2 = 2; 

%create function handle
f = @(x) cos(x); 

%call finite difference function
yderiv = derivative(f,x2) 

%use built-in to get differentiated function
ycheck = diff(eqn) 

With the output:

yderiv = -0.9093

ycheck =
-sin(x)

Any help on how to solve ycheck at x2, or a different approach to use would be most appreciated.

Cheers :)

Finn LeSueur
  • 479
  • 5
  • 18
  • 2
    `subs(ycheck, x2)` ? This substitutes the free symbolic variable (`x)` in `ycheck` by the value `x2` – Luis Mendo Aug 09 '14 at 12:51
  • Hey, if I edit the last part of my code to this: %use built-in to get differentiated function ycheck = diff(eqn); subs(ycheck, x, x2) Then I get an output of: yderiv = -0.9093 ans =-sin(2) – Finn LeSueur Aug 10 '14 at 08:15
  • Nevermind! If I put eval(subs(ycheck, x, x2)) in I get a numerical answer! Thank you very much for your help :) – Finn LeSueur Aug 10 '14 at 08:26

1 Answers1

-2

To calculate a derivative with finite differences you do not need the symbolic expressions you are using.

You need to:

  1. Select your delta, for example dx = 0.01
  2. Choose your range, let's say x = [0, 2*pi]. Create a variable for that range x = 0:dx:2*pi
  3. Evaluate the function, something like y = cos(x)
  4. Use the diff function
  5. Divide by your dx.
  6. Plot

The rest (getting the value of the derivative of y at x = 2) should be clear once you go through those steps.

gire
  • 1,105
  • 1
  • 6
  • 16