Why is the graph in this code becoming distorted?

6 views (last 30 days)
%% This is the code.
n=101;
nstep=100;
long=10.0;
h=long/(n-1);
dt=0.05;
D=0.05;
f=zeros(n,1);
y=zeros(n,1);
time=0.0;
for i=1:n
f(i)=0.5*sin(2*pi*h*(i-1));
end
for m=1:nstep
plot(f,'linewidth',2);
axis([1 n -2 2])
y=f;
for ii=2:n-1
f(ii)=y(ii)-0.5*(dt/h)*(y(ii+1)-y(ii-1)+D*(dt/h^2)*(y(ii+1)-2*y(ii)+y(ii-1)));
end
f(n)=y(n)-0.5*(dt/h)*(y(2)-y(n-1))+D*(dt/h^2)*(y(2)-2*y(n)+y(n-1));
time=time+dt;
title(sprintf('time = %3.2f',time))
pause(0.2)
end
As a result of running this code, the graph becomes distorted from the right end and stretched as 'time' increases. Is there something wrong that is causing this?

Accepted Answer

Mathieu NOE
Mathieu NOE on 19 Sep 2023
hello
maybe this ? I simply corrected one of your equation (looking at the one that follows , assumming the second was correct ) because there is a difference where you put your parenthesis
%% This is the code.
n=101;
nstep=100;
long=10.0;
h=long/(n-1);
dt=0.05;
D=0.05;
f=zeros(n,1);
y=zeros(n,1);
time=0.0;
i=1:n;
f=0.5*sin(2*pi*h*(i-1));
for m=1:nstep
plot(f,'linewidth',2);
axis([1 n -2 2])
y=f;
for ii=2:n-1
% f(ii)=y(ii)-0.5*(dt/h)*(y(ii+1)-y(ii-1)+D*(dt/h^2)*(y(ii+1)-2*y(ii)+y(ii-1)));
f(ii)=y(ii)-0.5*(dt/h)*(y(ii+1)-y(ii-1))+D*(dt/h^2)*(y(ii+1)-2*y(ii)+y(ii-1)); % correction based on the equation 2 lines below
end
f(n)=y(n)-0.5*(dt/h)*(y(2)-y(n-1))+D*(dt/h^2)*(y(2)-2*y(n)+y(n-1));
time=time+dt;
title(sprintf('time = %3.2f',time))
pause(0.2)
end

More Answers (0)

Categories

Find more on Spline Postprocessing in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!