Home > Back-end >  Can I optimise this Matlab for loop?
Can I optimise this Matlab for loop?

Time:04-02

I have the following code:

np = 25;
j = 1:3;
count = 2;

for i = 2:total_NN
   A(i) = B(j) * C(count, :)'; 
   count = count   1;

   % When this condition is met we will add to j and reset count:
   if rem(i-np, np-1) == 0 
       j = j   2; 
       count = 2; 
   end
end

I am trying to optimise it by removing the inner if statement and retaining its functionality. I tried doing this but it did not work nor eliminated the if statement:


for i = 2:total_NN
   A(i) = B(j) * C(count, :)'; 
   count = count   1;

   z = rem(i-np, np-1) != 0;
   j = j   2*z;

   if rem(i-np, np-1) == 0  
       count = 2; 
   end
end

What can I do? The if statement is slowing down my code immensely.

CodePudding user response:

You could calculate the if condition before the loop for every index

np = 25;
j = 1:3;
count = 2;
iArr = 2:total_NN;
r = (rem(iArr-np,np-1) == 0);

for ii = iArr 
   i = iArr(ii);

   A(i) = B(j) * C(count, :)'; 
   count = count   1;

   % When this condition is met we will add to j and reset count:
   if r(ii)
       j = j   2; 
       count = 2; 
   end
end

Without a complete example to test or sense of memory constraints it's hard to validate any further optimisations, but you could likely define

jArr = (1:3)   2*cumsum(r(:)); % all j values from the loop, select j=jArr(ii,:) for each loop

And something similar for count before the loop. At which point you may even be able to vectorise the entire matrix operation but that's beyond the scope of this question.

  • Related