Forward, Backwawrd, Central, and Perfect Difference

조회 수: 9 (최근 30일)
Bailey Smith
Bailey Smith 2018년 6월 14일
편집: Jan 2018년 6월 18일
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.
  댓글 수: 3
Jan
Jan 2018년 6월 15일
I agree with John. Please try it, post the code and ask a specific question. It is unlikely that the forum will do your work in exactly the way you need it.
Is this your homework?
Bailey Smith
Bailey Smith 2018년 6월 15일
An old homework, but no Matlab required. I've been wanting to take my old homeworks and code them into Matlab so that I can better understand the program before I take any advanced computing class. If I have time, I will try to get a code posted tonight or tomorrow.

댓글을 달려면 로그인하십시오.

채택된 답변

Ankita Bansal
Ankita Bansal 2018년 6월 18일
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

추가 답변 (1개)

Jan
Jan 2018년 6월 18일
편집: Jan 2018년 6월 18일
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by