Why is the graph in this code becoming distorted?

6 次查看(过去 30 天)
%% 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?

采纳的回答

Mathieu NOE
Mathieu NOE 2023-9-19
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by