%% Example 5.10
% V Cycle Multigrid for the Poisson Equation
%

%% Setup
close all;
clear N n x0 xN y0 yN dx dy x y X Y Q Ut U B num_vcycles err;

N = 32;
n = N + 1;

x0 = -1;
xN = 1;
y0 = -1;
yN = 1;

dx = (xN-x0)/N;
dy = (yN-y0)/N;

x = linspace(x0,xN,N+1);
y = linspace(y0,yN,N+1);

[X Y] = meshgrid(x,y);

Q = 2*(2-X.^2 - Y.^2);

%% True solution
Ut = (X.^2-1).*(Y.^2-1);

%% Multi-grid V-cycles
U = zeros(n,n);
B = -Q;

num_vcycles = 4;

for v = 1:num_vcycles
    U = mgv2d(U,B,3);
    err(v) = max(max(abs(U-Ut))) / max(max(Ut));
end

%% Plot
figure(1)
semilogy(err,'o-')
xlabel('iteration')
ylabel('error')
xlim([1 num_vcycles])
