Info

此问题已关闭。 请重新打开它进行编辑或回答。

How can the below code have better effieciency?

1 次查看(过去 30 天)
the below code performance in higher values is low and needs improvement.
is this code be able to be written in the form of parralle or any form that the improves the time running?
term3=0;
nrex =0;
Nx=512;
Ny=Nx;
ngrain=70;
glist = round(rand(1,70));
etas = rand(Nx*Ny,70);
en= zeros(1,70);
for i=1:70
en(i) = 0.4931;
end
for igrain=1:ngrain
for jgr=1:ngrain+nrex
if(glist(jgr)== 1)
den(igrain,jgr)=en(jgr)-en(igrain);
term3=term3-8/pi*(etas(:,igrain).*etas(:,jgr)).^0.5*den(igrain,jgr);
end
end
end
  1 个评论
Vladimir Sovkov
Vladimir Sovkov 2019-12-3
It looks, that your code ALWAYS results in a zero matrix den and a zero vector term3.
Are you sure this is what you really want? This case it does not need any computation at all, this solution can be written from the very beginning with a hugely better efficiency.
Generally, to improve the performance, you should avoid loops (they are slow in Matlab...) substituting them by matrix operations wherever possible. For example, your code
en= zeros(1,70);
for i=1:70
en(i) = 0.4931;
end
can be replaced by a more efficient code
en = 0.4931*ones(1,70);
You should also initialize all the arrays outside the loop, otherwise their resizing at every next step of a loop would take a huge amount of time. In your case, it means that the matrix den must be defined before the loop as, e.g. den = zeros(1st dimension, 2nd dimension).

回答(0 个)

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by