79 views (last 30 days)

I am working on an assignment to to create plot showing forward, backward and centeral differenciation using f=sin(pi*x) [-1:1] for different values of n.

This is what i've written for n=10 with plot

yf=zeros(1,10);

yb=zeros(1,10);

y=zeros(1,10);

for j=1:11

% n=10

xb=-1+(j-1)*.2;

xbb=-1+(j-2)*.2;

xf=-1+j*.2;

y(j)=sin(pi*xb); %u(xi)

yb(j)=sin(pi*xbb); %u(xi-dx)

yf(j)=sin(pi*xf); %u(xi+dx)

end

bd=y-yb; %backward dif

fd=yf-y; %forward dif

cd=(yf-yb)/2; %central diff

n=-1:.2:1;

f1=figure

fplot(@(t) pi*cos(pi*t),[-1,1]);

title('n=10')

hold on

plot(n,bd)

plot(n,fd)

plot(n,cd)

legend('derivative','backward','forward','center')

As I increase n to 100 as seen below, the curve becomes flatter (I would expect it to follow the curve more closely). Am I missing something conseptually or does the code not reflect the equations for forward, backward, and central difference.

for j=1:101

%n=100

xb=-1+(j-1)*.02;

xbb=-1+(j-2)*.02;

xf=-1+j*.02;

z(j)=sin(pi*xb); %u(xi)

zb(j)=sin(pi*xbb); %u(xi-dx)

zf(j)=sin(pi*xf); %u(xi+dx)

end

bd_1=z-zb;

fd_1=zf-z;

cd_1=(zf-zb)/2;

N=-1:.02:1; %hundo

f2=figure

fplot(@(t) pi*cos(pi*t),[-1,1]);

title('n=100')

hold on

plot(N,bd_1)

plot(N,fd_1)

plot(N,cd_1)

legend('derivative','backward','forward','center')

Bruno Luong
on 19 Sep 2019

Edited: Bruno Luong
on 19 Sep 2019

You forget to divide the differences by the time step (dt)

dt = 0.02

for j=1:101

xb=-1+(j-1)*dt;

xbb=-1+(j-2)*dt;

xf=-1+j*dt;

z(j)=sin(pi*xb); %u(xi)

zb(j)=sin(pi*xbb); %u(xi-dx)

zf(j)=sin(pi*xf); %u(xi+dx)

end

bd_1=(z-zb)/dt; % bug was HERE

fd_1=(zf-z)/dt; % bug was HERE

cd_1=((zf-zb)/2)/dt; % bug was HERE

N=-1:dt:1; %hundo

f2=figure

fplot(@(t) pi*cos(pi*t),[-1,1]);

title('n=100')

hold on

plot(N,bd_1)

plot(N,fd_1)

plot(N,cd_1)

legend('derivative','backward','forward','center')

Image Analyst
on 19 Sep 2019

Once you have y, or z, why not just compute differences numerically using conv()?

n = 11; % Whatever

kernel = zeros(1, 2*n+1);

kernel(n+1) = 1; % Center element of window

kernel(end) = -1; % Kernel will subtract first element in window from center element. Remember, convolution flips kernel!

yBackwards = conv(y, kernel, 'same');

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.