Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

% Define parameters

c = 2;
lx = 2;
ly = 2;
dx = 0.1;
dy = 0.1;
dt = 0.01;
tmax = 10;

% Define grid
x = 0:dx:lx;
y = 0:dy:ly;
t = 0:dt:tmax;

% Define initial conditions


u = zeros(length(x), length(y));
ut = zeros(length(x), length(y));
u(:, :) = 0;
ut(:, :) = 0;

% Define boundary conditions


u(1, :) = 0;
u(end, :) = 0;
u(:, end) = 0;
u(:, 1) = f(y) .* sin(5 * t(1));

% Define function for f(y)


function fy = f(y)
fy = y .* (ly - y);
end

% Implement McCormack scheme


for n=1:length(t)-1
% Predict step
u_pred_x_halfstep(:, :) = u(:, :) - c * dt / dx * (u(:, :) - circshift(u(:, :), [0, -1]));
u_pred_y_halfstep(:, :) = u_pred_x_halfstep(:, :) - c * dt / dy * (u_pred_x_halfstep(:, :) -
circshift(u_pred_x_halfstep(:, :), [-1, 0]));

% Correct step
u_corr_x_halfstep(:, :) = (u(:, :) + u_pred_x_halfstep(:, :)) / 2 - c * dt / dx / 2 *
(circshift(u_pred_y_halfstep(:, :), [0, 1]) - circshift(u_pred_y_halfstep(:, :), [0, -1]));
u_corr_y_halfstep(:, :) =(u_corr_x_halfstep(:,:) + u_pred_y_halfstep(:,:)) / 2 - c * dt / dy / 2 *
(circshift(u_pred_x_halfstep(:, :), [1, 0]) - circshift(u_pred_x_halfstep(:, :), [-1, 0]));

% Update u and ut
u(:, :) = u_corr_y_halfstep(:, :);
ut(:, :) = (u_corr_y_halfstep(:, :) - u(:, :)) / dt;
% Apply boundary conditions
u(1, :) = 0;
u(end, :) = 0;
u(:, end) = 0;
u(:, 1) = f(y) .* sin(5 * t(n+1));
end

% Plot results
[X,Y] = meshgrid(x,y);
surf(X,Y,u');
xlabel('x');
ylabel('y');
zlabel('u(x,y,t)');
title('2D Wave Equation Solution using McCormack Scheme');

) ‫جواب دقیق در نقطه‬

% Calculating the exact solution at point (1,1) and time t=10

fy = y.(y-ly);

u_exact = 0.5sin(50pi/4)sin(pi/2)sin(pi/2)fy(2);

% Calculating the numerical solution at point (1,1) and time t=10

unumerical = u(round(1/dx),round(1/dy),end);

% Calculating the error at point (1,1) and time t=10

error = abs(uexact - unumerical);


disp('Error using upwind first order scheme at point (1,1) and time t=10: ' num2str(error));

You might also like