Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate the discrete First Order Derivative of a function f using a Matrix Differential Operator in Matlab?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

%% 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)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading