Search code examples
matlabcomputational-geometry

Is there any way to vectorize the matlab code or another approach to reduce its running time?


Is there anyway to improve the below codes? It takes much time in higher values. I'd be appreciated if a solution for improving be advised.

term3=0;
ngrain=70;
etas = rand(512*512,70);
glist = round(1,70);
en = zeros(1,70);
for i=1:70
 en(i)=0.493;
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

Solution

  • please be more precise in the future. Here are a couple of hints to improve your coding:

    Building a vector out of constants can be achieved in several ways (unfortunately, you picked the least efficient one):

    • a for-loop (with or without pre-allocation of memory, you did allocate, so that is good!)
    • use 1 * constant => ones(1,70)*0.493
    • repeat the 1x1 matrix: repmat() => repmat(1,70,0.493) (this is the most efficient approach, you may check this using tic() and toc() )

    Anyway, this wasn't your bottleneck. You can do logical comparisons directly instead of looping and using if:

    lg = glist == 1;
    idx = find(lg);
    for i = 1:length(idx)
       jgr = idx(i)
    end
    

    Note that your example does not work because nrex is not defined. It would also be great if you format your code nicer (consistent spacing, indention, a naming that is a bit more intuitive)