How do i reduce running time in this code

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

回答 (1 件)

Swetha Polemoni
Swetha Polemoni 2020 年 12 月 20 日

0 投票

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.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2020 年 12 月 17 日

回答済み:

2020 年 12 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by