Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

How can the below code have better effieciency?

3 vues (au cours des 30 derniers jours)
Amir Torabi
Amir Torabi le 3 Déc 2019
Clôturé : MATLAB Answer Bot le 20 Août 2021
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 commentaire
Vladimir Sovkov
Vladimir Sovkov le 3 Déc 2019
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).

Réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by