How do i reduce running time in this code

2 vues (au cours des 30 derniers jours)
Tzach Berlinsky
Tzach Berlinsky le 17 Déc 2020
function [f , t] = jacobi2(n)
tic;
if n < 4
error ('n not in the range')
end
n=n^2;
b=zeros(n,1);
b(1,1)=1;
b(n,1)=1;
A = zeros(n,n);
for i=4:(n-3)
for j=4:(n-3)
if i==j
A(i,i)=4;
A(i,i+1)=-1;
A(i,i-1)=-1;
A(i,i+3)=-1;
A(i,i-3)=-1;
A(i+1,i)=-1;
A(i-1,i)=-1;
A(i+3,i)=-1;
A(i-3,i)=-1;
end
end
end
A(1,1)=4;
A(1,2)=-1;
A(3,2)=-1;
A(2,3)=-1;
A(2,1)=-1;
A(2,2)=4;
A(3,3)=4;
A(end,end)=4;
A(end-1,end-1)=4;
A(end-2,end-2)=4;
A(end-3,end-3)=4;
A(end-1,end)=-1;
A(end,end-1)=-1;
A(end-1,end-2)=-1;
A(end-2,end-1)=-1;
epsilon = 1e-3;
f = zeros(n,1);
counter = 0;
flag = 0;
L = tril(A,-1);
D = diag(A);
U = triu(A,1);
B = -1./D.*(L+U);
C = (1./D).*b;
while flag == 0
counter = counter+1;
if counter > 10000
error ('Too many iteration')
end
f_n = (B*f) + C;
if max(abs(f_n-f)/(f_n))<epsilon
flag = 1;
else
f = f_n;
end
end
t=toc;
end

Réponses (1)

Swetha Polemoni
Swetha Polemoni le 20 Déc 2020
Hi Tzach Berlinsky,
In the code you have provided using nested loops is not necessary. Since the body of loops is executed only when i==j, elimination of one loop can be an option. Replace the nested loops with the following.
for i=4:(n-3)
A(i,i)=4;
A(i,i+1)=-1;
A(i,i-1)=-1;
A(i,i+3)=-1;
A(i,i-3)=-1;
A(i+1,i)=-1;
A(i-1,i)=-1;
A(i+3,i)=-1;
A(i-3,i)=-1;
end
Here is the link to best practices that can be followed to improve performance. You may find it helpful.

Catégories

En savoir plus sur Biological and Health Sciences dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by