Asked by Bailey Smith
on 14 Jun 2018

Could someone please explain how to use the differences, especially with vectors? I would like to make a chart of the values of the four differences types, along with the corresponding x value. Say x=[0:0.2:0.6], y=sin(x), and yperfect=cos(x), how would I go about this?

UPDATE: This is the code I have to take the forward difference (first order).

function [out] = forwarddiff(x,y)

n=1;

L=length(x);

while n < L

out(n,1)=x(n);

out(n,2)=(y(n+1)-y(n))/(x(n+1)-x(n));

n=n+1;

end

out(L,1)=x(L);

out(L,2)=NaN;

end

X and Y values can be input by the user. My new question is: Would the second order forward difference look something like this?

function [out] = forwarddiff(x,y)

n=1;

L=length(x);

while n < L

out(n,1)=x(n);

out(n,2)=(y(n+2)-2*y(n+1)+y(n))/(x(n+1)-x(n))^2;

n=n+1;

end

out(L,1)=x(L);

out(L,2)=NaN;

end

I get an error about exceeding matrix dimensions when I run this.

Answer by Ankita Bansal
on 18 Jun 2018

Accepted Answer

Hi, in line

out(n,2)=(y(n+2)-2*y(n+1)+y(n))/(x(n+1)-x(n))^2;

you are getting error because you are trying to access y(n+2) at n=L-1.

Change your code to

function [out] = forwarddiff(x,y)

n=1;

L=length(x);

while n < L-1

out(n,1)=x(n);

out(n,2)=(y(n+2)-2*y(n+1)+y(n))/(x(n+1)-x(n))^2;

n=n+1;

end

out(L-1,1)=x(L-1);

out(L-1,2)=NaN;

end

Sign in to comment.

Answer by Jan
on 18 Jun 2018

Edited by Jan
on 18 Jun 2018

A shorter form of your 1st order forward difference:

function [out] = forwarddiff(x,y)

x = x(:); % Consider row vectors

y = y(:);

dy = (y(2:end) - y(1:end-1)) / (x(2:end) - x(1:end-1));

out = [x, [dy; NaN]];

end

If you really want to do this with a loop, care for a pre-allocation. Letting the output grow iteratively wastes a lot of resources.

See also the diff command and gradient.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## John D'Errico (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/405770-forward-backwawrd-central-and-perfect-difference#comment_578948

## Jan (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/405770-forward-backwawrd-central-and-perfect-difference#comment_578979

## Bailey Smith (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/405770-forward-backwawrd-central-and-perfect-difference#comment_579069

Sign in to comment.