MATLAB Answers

How do I reduce the running time of this program

24 views (last 30 days)
Tzach Berlinsky
Tzach Berlinsky on 17 Dec 2020
Edited: Jan on 22 Dec 2020
function [f , t] = jacobi1(n)
tic;
if n < 4
error ('n not in the range')
end
if rem(n,1)~=0
error ('n has to be a whole mumber')
end
n=n^2;
b=zeros(n,1);
b(1,1)=1;
b(n,1)=1;
A = zeros(n,n);
mymatrix=[-1 0 -1 4 -1 0 -1];
for i=1:3
A(i,1:i+3)=mymatrix(5-i:7);
A(n-(3-i),n-(6-i):n)=mymatrix(1:7-i);
end
for i=4:n-3
A(i,i-3:i+3) = mymatrix;
end
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

  0 Comments

Sign in to comment.

Answers (2)

Saurav Chaudhary
Saurav Chaudhary on 22 Dec 2020
Here is the link to best practices that can be followed to improve performance. You may find it helpful.

  0 Comments

Sign in to comment.


Jan
Jan on 22 Dec 2020
Edited: Jan on 22 Dec 2020
The profiler shows, that almost the complete time is spent in this line:
if max(abs(f_n - f) / f_n) < epsilon
Are you sure, that this calculates what you expect? For n=5, abs(f_n - f) / f_n is a 25x25 matrix. Using the max function replies a vector and to provide a scalare condition for the if command Matlab inserts an all() implicitly. Is this, what you want? Or maybe:
if max(abs((f_n - f) ./ f_n)) < epsilon
This is much faster, but another criterion and the results of the function are different.
Yur code does not contain meaningful comments, which explain, what you want to calculate. Then it is hard to guess, if you have implemente what was intented.

  0 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by