quadrature differentiation in matlab

To perform quadrature differentiation in MATLAB, one can follow these steps:

  1. Define the function which needs to be differentiated using inline or function_handle. For example, let us consider the function f(x) = cos(x).
main.m
f = inline('cos(x)');
22 chars
2 lines
  1. Define the interval over which the function needs to be differentiated. For example, let us consider the interval [0, pi/2].
main.m
a = 0;
b = pi/2;
17 chars
3 lines
  1. Choose the desired quadrature method to perform integration. For example, let us use the trapezoidal rule.
main.m
n = 100; % Number of intervals
x = linspace(a, b, n+1); % Generate n+1 equally spaced nodes
y = f(x); % Evaluate the function at each node
h = (b-a)/n; % Compute the step size
I_trap = h/2*(y(1) + 2*sum(y(2:end-1)) + y(end)); % Compute the trapezoidal rule approximation
271 chars
6 lines
  1. Differentiate the resulting approximated function using finite differences or other numerical differentiation methods. For example, let us use the central difference method with a step size of h.
main.m
D = zeros(size(y)); % Initialize the derivative vector
D(1) = (y(2)-y(1))/h; % Forward difference at first point
D(end) = (y(end)-y(end-1))/h; % Backward difference at last point
for i = 2:length(y)-1 % Central difference at all other points
    D(i) = (y(i+1) - y(i-1))/(2*h);
end
282 chars
7 lines
  1. Plot the original function and the resulting derivative.
main.m
plot(x, f(x), 'b-', x, D, 'r--');
legend('f(x)', 'f''(x)');
60 chars
3 lines

This will provide a plot of the original function in blue and the resulting derivative approximation in red.

gistlibby LogSnag