Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How can the below code have better effieciency?

1 回表示 (過去 30 日間)
Amir Torabi
Amir Torabi 2019 年 12 月 3 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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