Info
This question is closed. Reopen it to edit or answer.
First element of vector becoming equal to last element automatically?!?
2 views (last 30 days)
Show older comments
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
0 Comments
Answers (0)
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!