How can calcuate the lines of code efficiently?

조회 수: 2 (최근 30일)
Amir Torabi
Amir Torabi 2019년 12월 4일
댓글: Ahmad Nadeem 2021년 7월 14일
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);
grad=-(kron(T,E)+kron(E,T));%Tensor
%-- for periodic boundaries
for i=1:nx
ii=(i-1)*nx+1;
jj=ii+nx-1;
grad(ii,jj)=1.0;
grad(jj,ii)=1.0;
kk=nxny-nx+i;
grad(i,kk)=1.0;
grad(kk,i)=1.0;
end%for
grad = grad /(dx*dy);
  댓글 수: 1
Ahmad Nadeem
Ahmad Nadeem 2021년 7월 14일
hello brother!
I want to contact you. Can you please share your email or any other ID?
Thank You
Best Regards
Ahmad Nadeem
Hongik University, Seoul, South Korea

댓글을 달려면 로그인하십시오.

채택된 답변

Stephan
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);
grad=-(kron(T,E)+kron(E,T));%Tensor
%-- for periodic boundaries
ii=(0:nx-1).*nx+1;
jj = ii+nx-1;
grad(ii,jj)=1.0;
grad(jj,ii)=1.0;
kk=(nxny-nx+1):nxny;
grad(1:nx,kk)=1.0;
grad(kk,1:nx)=1.0;
grad = grad /(dx*dy);
toc
Elapsed time is 0.145899 seconds.
Your code:
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);
grad=-(kron(T,E)+kron(E,T));%Tensor
%-- for periodic boundaries
for i=1:nx
ii=(0:nx-1).*nx+1;
jj=ii+nx-1;
grad(ii,jj)=1.0;
grad(jj,ii)=1.0;
kk=nxny-nx+i;
grad(i,kk)=1.0;
grad(kk,i)=1.0;
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);
grad=-(kron(T,E)+kron(E,T));%Tensor
%-- for periodic boundaries
for i=1:nx
ii=(0:nx-1).*nx+1;
jj=ii+nx-1;
grad(ii,jj)=1.0;
grad(jj,ii)=1.0;
kk=nxny-nx+i;
grad(i,kk)=1.0;
grad(kk,i)=1.0;
end
ii=(0:nx-1).*nx+1;
jj = ii+nx-1;
grad(ii,jj)=1.0;
grad(jj,ii)=1.0;
kk=(nxny-nx+1):nxny;
grad(1:nx,kk)=1.0;
grad(kk,1:nx)=1.0;
grad1 = grad /(dx*dy);
expect_all_zeros = grad1-grad
expect_all_zeros =
All zero sparse: 262144×262144
Appears to work fine...
  댓글 수: 4
Amir Torabi
Amir Torabi 2019년 12월 5일
i checked it again. yes your answer is correct. Thanks.
Ahmad Nadeem
Ahmad Nadeem 2021년 7월 14일
I didnt understand this code can you please help me to understand this code?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by