HOW DO I DO THAT IN MATLAB SERIES?
In this series, I am answering questions that students have asked me about MATLAB. Most of the questions relate to a mathematical procedure.
Contents
TOPIC
How do I find the first derivative of a discrete function y(x) if the x values are equidistant.
SUMMARY
Language : Matlab 2010a; Authors : Autar Kaw and Sri Garapati; Mfile available at Last Revised : January 17, 2012; Abstract: This program shows you how to differentiate discrete data if the x values are equally spaced
clc
clear all
INTRODUCTION
disp('ABSTRACT') disp(' This program shows you how to differentiate discrete data if') disp(' the x values are equally spaced ') disp(' ') disp('AUTHOR') disp(' Autar Kaw and Sri Garapati of http://autarkaw.wordpress.com') disp(' ') disp('MFILE SOURCE') disp(' http://numericalmethods.eng.usf.edu/blog/discrete_diff_equidistant_blog.m') disp(' ') disp('LAST REVISED') disp(' January 17, 2012') disp(' ')
ABSTRACT This program shows you how to differentiate discrete data if the x values are equally spaced AUTHOR Autar Kaw and Sri Garapati of http://autarkaw.wordpress.com MFILE SOURCE http://numericalmethods.eng.usf.edu/blog/discrete_diff_equidistant_blog.m LAST REVISED January 17, 2012
INPUTS
% Inputs assuming % that three or more points are given % all x values are equidistant % x values are in ascending or descending order. x=[2.3 3.4 4.5 5.6 6.7 7.8]; y=[4.6 7.9 13.0 12.3 3.2 1.9];
DISPLAYING INPUTS
disp(' ') disp('INPUTS') % Creating a matrix to print input data as a table data=[x;y]'; disp(' X Data Y Data') % Printing the input data as a table disp(data)
INPUTS X Data Y Data 2.3000 4.6000 3.4000 7.9000 4.5000 13.0000 5.6000 12.3000 6.7000 3.2000 7.8000 1.9000
THE CODE
% n returns the number of data points n=length(x); % delta is the distance between consecutive x values delta=x(2)-x(1); % "dy" is an array which stores the value of the derivative at each x-value % finding the derivative from the 2nd order accurate forward divided % difference formula at the first data point dy(1)=(-y(3)+4*y(2)-3*y(1))/(2*delta); % finding the derivative from the 2nd order accurate central divided % difference formula at the second to (n-1)th data point for i=2:1:n-1 dy(i)=(y(i+1)-y(i-1))/(2*delta); end % finding the derivative from the 2nd order accurate backward divided % difference formula at the first data point dy(n)=(y(n-2)-4*y(n-1)+3*y(n))/(2*delta); % creating a matrix with input data and calculated derivative value at % each data point for printing as a table xdy=[x' y' dy'];
DISPLAYING OUTPUTS
disp(' ') disp('OUTPUTS') disp(' XData YData Derivative') % printing the input data points and calculated derivative values(Outputs) disp(xdy)
OUTPUTS XData YData Derivative 2.3000 4.6000 2.1818 3.4000 7.9000 3.8182 4.5000 13.0000 2.0000 5.6000 12.3000 -4.4545 6.7000 3.2000 -4.7273 7.8000 1.9000 2.3636