I want to calculate a discrete approximation of df/dx in Matlab using a vector f representing the function and a Matrix D representing a differential operator. f in this example is a simple sine wave such that the df/dx should be cos(x).

The differential approximation df/dx seems to be correct but the amplitude scaling is incorrect and the last and first samples are out of line. Why?

Matlab code:

%% Sandbox Finite Difference
clear
clc
close all

% set physical values
f=1000;
c=343.21;
lambda=c/f;
w=2*pi*f;
k=w/c;
dx=0.01;
x_max=1;
x=0:dx:x_max;

% initialize function f
f=sin(k.*x);

% Build Differential Operator D
di= ones(1,length(f)-1);
D = diag(di,1);
D = D+diag(-di,-1);
% scale D with 1/(2*dx)
D = D*(1/(2*dx));

% Apply Differential Operator on f
f_1diff=D*f';

% plot f and df/dx
plot(f)
hold on
plot(f_1diff)
1

There are 1 best solutions below

0
On BEST ANSWER

Your scaling factor for D should be 1/(2*dx*k). as the derivative of f(x)/dx contains k as constant.

Also, the end points are wrong because you have not considered what boundary conditions you give your operator. The first row is scale*[0 1 0 ....], there is no -1. You decide how to handle this, but of course no decision is perfect because the value you need does not exist (f(0), or f(end+1) for the other side.