Is this proper use of backward difference approxiamation?

86 views (last 30 days)
This is the question prompt given:
Assume you have the data vectors x and y. Plot the data and the derivative of the data using the backward difference approximation on the same axis. You should be able to do this regardless of how many data points are in x and y. Assume x and y always have the same amount of elements.
To answer this I produced this:
% Define the data vectors x and y
x = linspace(0, 10, 100);
y = sin(x);
% Compute the derivative of the data using the backward difference approximation
dy = diff(y) ./ diff(x);
% Plot the data and the derivative on the same axes
plot(x, y);
hold on;
plot(x(1:end-1), dy);
Does this satisfy the rubric of
Properly plots both data sets using backwards difference approximation technique
My argument including the following:
When googling the diff approximation I found this on mathworks
Y = diff(X) calculates differences between adjacent elements of X along the first array dimension whose size does not equal 1:
  • If X is a vector of length m, then Y = diff(X) returns a vector of length m-1. The elements of Y are the differences between adjacent elements of X.Y = [X(2)-X(1) X(3)-X(2) ... X(m)-X(m-1)]
  • Use the diff function to approximate partial derivatives with the syntax Y = diff(f)/h, where f is a vector of function values evaluated over some domain, X, and h is an appropriate step size.For example, the first derivative of sin(x) with respect to x is cos(x), and the second derivative with respect to x is -sin(x). You can use diff to approximate these derivatives.
To use the backwards difference approximation in Matlab, you can simply call the diff() function with the function values and step size as arguments. Is there a reason that would be inappropriate use in this case?
The response I got was: The backward difference approximation technique will plot x(2:end) not x(1:end-1). You have a fundamental misunderstanding of the two.

Answers (1)

Askic V
Askic V on 16 Dec 2022
The difference can be best seen on an example:
h = 0.1;
x = 0:h:6;
F = sin(x);
x_fw = x(1:end-1);
dF_fw=(F(2:end)-F(1:end-1))/h;
plot(x_fw, dF_fw);
hold on
x_back = x(2:end);
dF_back=(F(2:end)-F(1:end-1))/h;
plot(x_back, dF_back);
% original derivation dF = cos(x)
plot(x, cos(x))
legend('Forward', 'Backward', 'Actual');

Categories

Find more on Discrete Data Plots in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!