Speeding up code by avoiding FOR, IF loops
    10 views (last 30 days)
  
       Show older comments
    
Hi all, I have a question about how to speed up my code. I've been taught that for/if loops in matlab generally aren't great ideas, so I want to find a way to avoid them in the following code.
If you have suggestions on how to make these calculations outside of loops, I'd really appreciate it.
for i = 1:length(uniqueID)
  for j = 1:length(timeList)
    x = strmatch(uniqueID(i),idSeriesMonthly)
    y = blsDataMonthly(x,[1 4])'
    for k = 1:length(y)
      if blsDataSeries(1,j) == y(1,k)
        blsDataSeries(i + 1,j) = y(2,k)
      end
    end
  end
end
0 Comments
Answers (1)
  Jan
      
      
 on 3 Mar 2012
        The rumor, that for-loops are slow in general concern the versions before 6.5 (July 2002). In modern Matlab versions the JIT can accelerate loops substantially.
In opposite to this strmatch is really slow. Better use strcmp or strncmp.
In addition the output to the command window consumes much time also. So append a semicolon after each assignment command.
You overwrite blsDataSeries(i + 1,j) repeatedly. So better start the innermost loop from the back and stop after the first match:
for k = length(y):-1:1
  if blsDataSeries(1,j) == y(1,k)
    blsDataSeries(i + 1,j) = y(2,k);
    break;  % Break out of the k-loop
  end
end
Avoid the transposition of y.
[EDITED]
nTime         = length(timeList);
blsDataSeries = zeros(length(uniqueID) + 1, nTime);  % pre-allocate!
q = zeros(1, nTime);
for i = 1:length(uniqueID)
  aID = uniqueID{i};
  x   = strncmp(aID, idSeriesMonthly, length(aID));
  if sum(x) > 2
    y1   = blsDataMonthly(x, 1);
    y4   = blsDataMonthly(x, 4);
    q(:) = NaN;  % Re-use existing memory
    for a = 1:length(y)
      y1a = y1(a);
      for b = nTime:-1:1
        if y1a == timeList(b)
          q(b) = y4(a);
          break;  % Break b-loop after the last occurrence
        end
      end
    end
    blsDataSeries(i + 1, :) = q;
  end
end
2 Comments
  Jan
      
      
 on 4 Mar 2012
				Is blsDataSeries pre-allocated properly? If not, this array grows in each iteration, which wastes a lot of time. See [EDITED]. It would be easier to help, if the types and sizes of the used variables are explained.
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
