samedi 19 décembre 2015

Is there a way to optimize or maybe even vectorize this? (MATLAB)

I have an if statement within two loops, it runs too slow and I think it can be optimized. NF_zeta is a 2D array of trues and falses.

for k = 2:Nx
    for l = 2:Ny
        if NF_zeta(l,k)
            z2(l,k) = z1(l,k) - optVar2*(U2(l,k) - U2(l,k-1) + V2(l,k) - V2(l-1,k));
        end
    end
end

Here are the results of a profiler http://ift.tt/1Mn6KfN

I tried with single loop in which the conditional statement was taken care of. Something similar to what is done for one loop for [1 4 5], I wrote

for idx = NF_zeta_v
    z2(idx(1),idx(2)) = z1(idx(1),idx(2)) - optVar2*(U2(idx(1),idx(2)) - U2(idx(1),idx(2)-1) + V2(idx(1),idx(2)) - V2(idx(1)-1,idx(2)));
end

where NF_zeta_v is created in advance like this

c_z = 1;
for l = 1:Ny
    for k = 1:Nx
        if NF_zeta(l,k)
           NF_zeta_v(:,c_z) = [l;k];
           c_z = c_z + 1;
        end
    end
end

It took almost twice as long. The results of a profiler http://ift.tt/1RviPYi

What else can I try, any suggestions?

Aucun commentaire:

Enregistrer un commentaire