[Math] Finite Difference Method MATLAB Program

MATLABnumerical methods

I am a beginner to MATLAB.
I am trying to create a MATLAB program for the finite difference which is to calculate potential in a grid.
I have to include a condition such that the iterations stop once the difference between the last two iterations of potential for all nodes is less than 0.001.
Here v(i,j) represents the potential.

I was thinking of a IF loop, but did not know how to end it/exit it.
Say like v(i,j) – v(i-1,j-1) = 0.001.

clc
clear all 
close all

v1 =0;  
v3 = 139;
v2 = 0;
v4 = 0;

ni = 200; % no. of iterations
nx = 6;
ny = 5;

v = zeros(nx,ny);

for i =2:nx-1
   v(i,1) = v1;
   v(i,ny) = v3;

end
for j=2:ny-1
  v(1,j) = v4;
  v(nx,j) = v2;

end
   v(1,1) = 0.5*(v1 + v4)
   v(nx,1)  = 0.5 * (v1 +v2)
   v(1,ny) = 0.5*(v3 + v4)
   v(nx,ny) = 0.5* (v2+v3)

for k = 1:ni
  for i =2:nx-1
    for j = 2:ny-1
        v(i,j) = 0.25*(v(i+1,j)+v(i-1,j) +v(i,j+1)+v(i,j-1));
    end

  end
end

Best Answer

A classical approach is the following. Always store the previous solution along with the new one. Then use a while loop that continues as long as the criterion is not fulfilled. For example one can continue as long as

$$\max|v -v_{\text{old}}|>0.001 $$

also known as the infinity norm, i.e. $\|v-v_{\text{old}}\|_{\infty}>0.001$.

v_old = zeros(size(v));
k = 0;
NormDiff = 1; % inititialize some norm value to enter loop.
while k<max_iter && NormDiff>0.001
   --- update iteration on v here ---
   k = k + 1; % Update iteration number.
   NormDiff = norm(v-v_old,'Inf'); % Calculate the norm difference.
   v_old = v; % Store the new iteration as the old one.
end
Related Question