How do i reduce running time in this code

조회 수: 3 (최근 30일)
Tzach Berlinsky
Tzach Berlinsky 2020년 12월 17일
답변: Swetha Polemoni 2020년 12월 20일
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일
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.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by