Clear Filters
Clear Filters

Info

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

Double FOR loop - any way to speed up? (Electrical potencial computation - CODE INCLUDED)

1 view (last 30 days)
Hi.
I have a program which calculates an electrical potencial around stormy cloud, which is placed above the lighthouse. I compute this using "Finite difference method". A "box" is an 320x320 matrix with known boundary conditions (V=0) and V of a cloud is also known (V1). V of a lighthouse is 0.
Now I have 2 "for" loops which go from left to right side of a matrix and from top to bottom. Every round I compare new and old value of matrix. When they differentiate for less than 0.01 I am happy and quit.
That method works OK, except it is very slow. Do you have any idea how to speed it up? Is possible not to use double "for" loops? Is there any other way instead of these nested loops?
Below is only that part of a program, which includes these loops:
Thanks
%%Finite difference method
n = 320;
V = zeros(n);
% Some of the elements of V should be V1
V(CloudHeight,(n/2-CloudWidth/2)+1:(n/2+CloudWidth/2)) = V1;
% Boundary conditions
V(1:n,1) = zeros(n,1);
V(1:n,n) = zeros(n,1);
diff = 100;
while diff > 0.01 % Desired final accuracy
VV = V;
for i = 2:n-1 % "For" along the rows of matrix V
for j = 2:n-1 % "For" along the columns of matrix V
% Some of the elements of V should be 0
V(UpperHeight:MiddleHeigt, ExtremeLeft:ExtremeRight) = 0;
V(MiddleHeigt:n, Left:Right) = 0;
% Some of the elements of V should be V1
V(CloudHeight,(n/2-CloudWidth/2)+1:(n/2+CloudWidth/2)) = V1;
% Iteration equation
V(i,j) = (1/6)*(2*V(i,j+1)+2*V(i,j-1)+V(i+1,j)+V(i-1,j));
end
end
% Watching the difference between old and new value of V
diff = max(max(abs(V-VV)));
end
% At the end I set the predetermined elements of V to the required value
% for the last time
V(UpperHeight:MiddleHeigt, ExtremeLeft:ExtremeRight) = 0;
V(MiddleHeigt:n, Left:Right) = 0;
V(CloudHeight,(n/2-CloudWidth/2)+1:(n/2+CloudWidth/2)) = V1

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!