Filter löschen
Filter löschen

1D diffusion equation with different dx and dt

2 Ansichten (letzte 30 Tage)
Phoebe Tyson
Phoebe Tyson am 12 Mär. 2020
Beantwortet: Ayush Gupta am 4 Jun. 2020
I'm trying to compare and approximation of the 1D diffusion equation with the real value with different step size dx=h and dt. Because there are more dt step sizes, I don't know how to get the approximation for each x and t.
Here is my function:
function [t,u]=fixed_diffusion(h,dt,u0,ux0,uxN,x0,xN,uexact,T,theta)
L=xN-x0; %length of approximation
N=L/h;%spatial mesh size
x=x0:h:xN;%x values in a vector
u=u0(x);%implementing inital condition at t=0 and storing in u
dudt=zeros(N+1,1);
t=0:dt:T;%t values in a vector
for j=2:length(t)
for i=2:N
dudt(i)=(u(i+1)-2*u(i)+u(i-1))/(h^2);%approximating dudt using finite difference method
end
dudt(1)=(u(2)-2*u(1)+ux0)/(h^2);%boundary conditions
dudt(N+1)=(uxN-2*u(N+1)+u(N))/(h^2);
u(j)=u(j)+dudt(j)*dt;%eulers method to get approximation for u
ureal=zeros(N+1,1);
for i=1:N+1
ureal(i)=uexact(x(i),t(i));
end
figure(1)
plot(x,u,'.',x,ureal,'--');
legend('Approx:','True:');
err=norm((u-ureal),2);
T1=table(N,x,u,ureal,err)
pause(0.1)
end
end
And the script I am running with the input values
ux0=0;
uxN=0;
h=0.1;
dt=0.0005;
theta=0; %tells us it is eulers method
T=0.1;
x0=0;
xN=1;
u0=@(x)sin(pi*x);
uexact=@(x,t)exp((-pi^2).*t).*sin(pi.*x);
[t,u]=fixed_diffusion(h,dt,u0,ux0,uxN,x0,xN,uexact,T,theta)
When I try and create the table, I've noticed u is a matrix so it won't create a table, or calculate the correct errors. How can I fix this?
Error using table (line 232)
All table variables must have the same number of rows.
Error in fixed_diffusion (line 23)
T1=table(x,u,ureal,err)
Error in CW1q2 (line 12)
[t,u]=fixed_diffusion(h,dt,u0,ux0,uxN,x0,xN,uexact,T,theta)
  2 Kommentare
darova
darova am 12 Mär. 2020
Can't you return u matrix separately?
You don't return T1 by the way
Phoebe Tyson
Phoebe Tyson am 12 Mär. 2020
I want to return a table showing the approx of u at the final time, the real exact u and the error

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Ayush Gupta
Ayush Gupta am 4 Jun. 2020
The table function gives error because the u matrix is not created properly and in line
u(j)=u(j)+dudt(j)*dt;%eulers method to get approximation for u
the script is trying to access values out of bound of u which are not present as j runs from 2 to 201 whereas u is a matrix of 1x11 and after 11 it will give the error Index exceeds the number of array elements (11).
Because of this the table function is giving the error of All table variables must have the same number of rows.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by