0
0
MATLABdata~5 mins

Numerical differentiation in MATLAB

Choose your learning style9 modes available
Introduction

Numerical differentiation helps us find the slope or rate of change of a function when we don't have its exact formula. It uses numbers and simple calculations to estimate this.

When you have data points from an experiment and want to find how fast something changes.
When the function is too complex or unknown, but you can calculate values at certain points.
When you want to approximate derivatives in simulations or engineering problems.
When you want to check the behavior of a function near a point without calculus formulas.
Syntax
MATLAB
f_prime = (f(x + h) - f(x)) / h

This is called the forward difference formula.

Here, h is a small number representing a tiny step.

Examples
Estimate the derivative of x^2 at x = 2 using a small step h.
MATLAB
h = 0.001;
x = 2;
f = @(x) x^2;
f_prime = (f(x + h) - f(x)) / h;
Estimate the derivative of sin(x) at x = 3.
MATLAB
h = 0.001;
x = 3;
f = @(x) sin(x);
f_prime = (f(x + h) - f(x)) / h;
Use the central difference formula for better accuracy at x = 1.
MATLAB
h = 0.001;
x = 1;
f = @(x) exp(x);
f_prime = (f(x + h) - f(x - h)) / (2*h);
Sample Program

This program estimates the derivative of the function x^3 + 2x^2 - x + 1 at x = 1.5 using both forward and central difference methods.

MATLAB
h = 1e-5;
x = 1.5;
f = @(x) x^3 + 2*x^2 - x + 1;

% Forward difference
f_prime_forward = (f(x + h) - f(x)) / h;

% Central difference
f_prime_central = (f(x + h) - f(x - h)) / (2*h);

fprintf('Forward difference derivative at x=%.2f: %.5f\n', x, f_prime_forward);
fprintf('Central difference derivative at x=%.2f: %.5f\n', x, f_prime_central);
OutputSuccess
Important Notes

Choosing a very small h improves accuracy but can cause rounding errors.

Central difference is usually more accurate than forward difference.

Summary

Numerical differentiation estimates slopes using nearby points.

Forward difference uses one side; central difference uses both sides for better accuracy.

Small step size h is important but balance is needed to avoid errors.