2
votes

I am just starting to learn Matlab, and I would be very grateful if someone could clarify my confusion...

I am trying to solve a non-uniform transport equation using the Lax-Wendroff scheme, with the code below. Matlab tells me that there are errors in the last line of the code (U(j+1,2:N)=(1/2).*sigma...), that is, 1. Error using *; 2. Inner matrix dimensions must agree.

I know the dimensions of sigma and U's are not compatible (as matrices), but I have no idea (and experience) on how to fix this... There's no problem with the formula, but I really find it hard to deal with the code.

    a = -10;
    b = 10;
    delta_x = (b-a)/N;
    x = a:delta_x:b;

    tfinal = 2;
    delta_t = tfinal/M;
    t = 0:delta_t:tfinal;

    c = 3-2.* exp(-(1/4).*(x.^2)) ;

    sigma = c.*(delta_t/delta_x);

    U=zeros(M+1,N+1);
    U(1,:)=f(x);

    for j=1:M
    U(j+1,2:N)=(1/2).*sigma.*(sigma-1).*U(j,3:N+1)-((sigma).^2-1).*U(j,2:N)+(1/2).*sigma.*(sigma+1)*U(j,1:N-1);
    end

Thank you so much!

1

1 Answers

0
votes

I have added the size of each variable as a comment and formatted the code a bit. It is still the same code as you posted.

a = -10;
b = 10;
delta_x = (b-a)/N;
x = a:delta_x:b;                   % x: 1 x ( N + 1 )

tfinal = 2;
delta_t = tfinal/M;
t = 0:delta_t:tfinal;              % t: 1 x ( M + 1 )

c = 3-2.* exp(-(1/4).*(x.^2)) ;    % c: 1 x ( N + 1 )

sigma = c.*(delta_t/delta_x);      % sigma: 1 x ( N + 1 )

U=zeros(M+1,N+1);                  % U: ( M + 1 ) x ( N + 1 )
U(1,:)=f(x);                       % Assuming f(x): 1 x ( N + 1 ), otherwise you will get an error here.

for j=1:M
    U(j+1,2:N) = (1/2).*sigma.*(sigma-1).*U(j,3:N+1) ...
                -((sigma.^2)-1).*U(j,2:N) ...
                +(1/2).*sigma.*(sigma+1)*U(j,1:N-1);
end

You will notice that in first line of for-loop you are multiplying sigma (of size 1 x ( N + 1 )) with U(j, 3:N+1) (size: 1 x (N - 1)). This will not work. You do the same thing for next two lines of for-loop, where the size of U(j,...) is not same as size of sigma.

I do not know what the actual equation looks like, so can not say for sure how you need to correct for the size mismatch. But you can try replacing sigma by say sigma(3:N+1) or something equivalent to get the right size.