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)