# How can calcuate the lines of code efficiently?

1 ビュー (過去 30 日間)
Amir Torabi 2019 年 12 月 4 日
コメント済み: Amir Torabi 2019 年 12 月 5 日
Hello. This code calculates the Laplacian. I am looking for reducing the time running of it. My main aim is improving the performance of loop running time.
Thanks
%%%code
nx=512;
ny=nx;
dx=1;
dy=dx;
format long;
nxny=nx*ny;
r=zeros(1,nx);
r(1:2)=[2,-1];
T=toeplitz(r);
E=speye(nx);
%-- for periodic boundaries
for i=1:nx
ii=(i-1)*nx+1;
jj=ii+nx-1;
kk=nxny-nx+i;
end%for

#### 0 件のコメント

サインイン to comment.

### 採用された回答

Stephan 2019 年 12 月 4 日
Yes, you can if you avoid using a loop and vectorize your code - see here:
tic
%%%code
nx=512;
ny=nx;
dx=1;
dy=dx;
format long;
nxny=nx*ny;
r=zeros(1,nx);
r(1:2)=[2,-1];
T=toeplitz(r);
E=speye(nx);
%-- for periodic boundaries
ii=(0:nx-1).*nx+1;
jj = ii+nx-1;
kk=(nxny-nx+1):nxny;
toc
Elapsed time is 0.145899 seconds.
tic
%%%code
nx=512;
ny=nx;
dx=1;
dy=dx;
format long;
nxny=nx*ny;
r=zeros(1,nx);
r(1:2)=[2,-1];
T=toeplitz(r);
E=speye(nx);
%-- for periodic boundaries
for i=1:nx
ii=(0:nx-1).*nx+1;
jj=ii+nx-1;
kk=nxny-nx+i;
end
toc
Elapsed time is 11.333450 seconds.
Are the results correct? - to check this we call one of the results grad1 and subtract grad1 from grad:
nx=512;
ny=nx;
dx=1;
dy=dx;
format long;
nxny=nx*ny;
r=zeros(1,nx);
r(1:2)=[2,-1];
T=toeplitz(r);
E=speye(nx);
%-- for periodic boundaries
for i=1:nx
ii=(0:nx-1).*nx+1;
jj=ii+nx-1;
kk=nxny-nx+i;
end
ii=(0:nx-1).*nx+1;
jj = ii+nx-1;
kk=(nxny-nx+1):nxny;
expect_all_zeros =
All zero sparse: 262144×262144
Appears to work fine...

#### 3 件のコメント

Amir Torabi 2019 年 12 月 4 日
kk in your code first code is an empty array!.
Stephan 2019 年 12 月 4 日
Sure, for me not. Check it with
whos kk
For me kk is 1x512 sized. Also if it would be empty, why are the results the same like in the code you provided?
Amir Torabi 2019 年 12 月 5 日
i checked it again. yes your answer is correct. Thanks.

サインイン to comment.

### その他の回答 (0 件)

サインイン してこの質問に回答します。

Translated by