Info

This question is closed. Reopen it to edit or answer.

First element of vector becoming equal to last element automatically?!?

1 view (last 30 days)
I am using the following code to solve the laplace equation.
The issue I am facing is that the first element of norm_err which I am setting to 1 is automatically being reset to the last element on each iteration of the while loop. Why is this happening?
clear; clc; close all;
%==================================================
% MAKE n LIST
n_list = [5, 10, 15];
%==================================================
% SOLVE LAPLACE EQUATION FOR EACH n
% PreAllocation
iterations = zeros(1, length(n_list));
for k = 1:length(n_list)
% Keep Track of the iterations
k
%==================================================
% MAKE A MATRIX TO HOLD AN n x n GRID
n = n_list(k);
% actual_grid = zeros(n, n);
%==================================================
% INITIALIZE THE GRID
% iterated_grid = zeros(n, n);
amplitude = 1;
iterated_grid = amplitude * rand(n, n);
%==================================================
% SET BOUNDARY CONDITIONS
x0 = 0;
y0 = 0;
xf = 1;
yf = 1;
xx = linspace(x0, xf, n);
yy = linspace(y0, yf, n);
delta_x = (xf - x0) / (n - 1);
delta_y = (yf - y0) / (n - 1);
[X, Y] = meshgrid(xx, yy);
actual_grid = X.^2 - Y.^2;
% Set boundary of iterated grid
iterated_grid(1, :) = actual_grid(1, :);
iterated_grid(length(yy), :) = actual_grid(length(yy), :);
iterated_grid(:, 1) = actual_grid(:, 1);
iterated_grid(:, length(xx)) = actual_grid(:, length(xx));
%==================================================
% SET AVERAGE VALUE FOR EACH POINT, ITERATE N TIMES
tolerance = 1e-6;
copy_grid = iterated_grid;
norm_err{k}(1) = 1;
iterations(k) = 0;
while norm_err{k}(iterations(k) + 1) > tolerance
iterations(k) = iterations(k) + 1;
% Run the iteration through the interior of the matrix
iterated_grid(2:end-1, 2:end-1) = (0.25) * (iterated_grid(1:end-2, 2:end-1) + iterated_grid(3:end, 2:end-1) + iterated_grid(2:end-1, 1:end-2) + iterated_grid(2:end-1, 3:end) );
difference_grid = iterated_grid - copy_grid;
norm_err{k}(iterations + 1) = sqrt(sum(sum(difference_grid(2:end-1, 2:end-1).^2)) / ((n-2)*(n-2)));
copy_grid = iterated_grid;
end
format long
disp(norm_err{k}([1, 2, 3, end]));
end
k = 1
0.000000720425189 0.393537402267598 0.169809678519038 0.000000720425189
k =
2
0.000000950157662 0.423949692990376 0.289627916298907 0.000000950157662
k =
3
1.000000000000000 0.333282811338901 0.163630143300983 0.000000975445388

Answers (0)

This question is closed.

Community Treasure Hunt

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

Start Hunting!