Hi, I have edited your code as shown below
U(2:end-1,j+1) = -(U(2:end-1,j)-U(1:end-2,j))*dt/(dx)+B2*(U(3:end,j)-2*U(2:end-1,j)+U(1:end-2,j))*dt/(dx^2)+U(2:end-1,j);
Ur(:,j+1) = 0.5*erfc((x-t(j+1))/(2*B2*t(j+1)^0.5))+0.5*exp(x/B2).*erfc((x+t(j+1))/(2*B2*t(j+1)^0.5));
title('Analytical Solution')
EXPLANATION
First, you were mis-calculating B, because you wrote B = (1/878)^1/2, which first raises the content of the brackets to the power of 1 and then divides the result by 2. I avoided any mistake by just defining B^2 directly.
This was your only actual mistake, the rest of the code was fine.
However, I have changed a couple of things.
- I have set the value dt to be computed automatically from the value of dx (using stability criterion). In this way, you can change the value of dx at your discretion without having to manually compute the new dt.
- I have eliminated the inner loop in the PDE solving, because you can code spatial discretization making intelligent use of indexing (see code).
- I have approximated the first order spatial derivative with a first order accurate finite difference using an upwind scheme, which is notoriously better for convective terms.
With these changes, you get the following plot
So numerical and analytical solutions do not match and there's a large error.
However, I think there might be some problem with how the analytical solution is formulated.
In fact, given the presence of the second-order spatial derivative (i.e., diffusion), I would expect a behaviour like the one yielded by the numerical integration, while the analytical solution seems to only advect the initial profile.
Could you double check the correctness of the analytical solution?