Monthly Archives: August 2012

Going ‘for’ a loop in Matlab syntax

For the most part scripting in Matlab should avoid the use of for loops. Generally the operations can be much quicker in the ‘vectorized’ notation that Matlab has worked hard to optimize. The link above is worth reading although as pointed out by in the Matlab Hypertext Ref,¬†Matlab is not necessarily the best choice for real time tasks anyway (it’s a scripting language!)… so getting the code right is more important than getting it done fast.

However if you do use for loops there are major differences between those in Matlab and those in other languages like C++. In other languages you may be able to write something like

for( int x = 0; x <= 10; x++){
x = 11;
}

//And the loop executes once!

So the loop goes around once (x=0) and then stops because (x=11 !<= 10). This is not really surprising until you look into what Matlab does in a similar situation:

 

for x = 0:1:10
x = 11;
end;
%% the loop runs 11 times

So this is not what would generally be expected. We told Matlab to go from 0 to 10 in increments of one just like our C++ code but we got a drastically different result. If we printed out the values of x between assignment and just after assignment we would see that the variable oscillates back and forth between the assigned value (10) and the incrementing values 0 to 10. This is a result of the vectorization of the loop, which includes an indexing that the user does not see. The variable x is not incremented by x++ or x=x+1, rather Matlab sub-indexes the index x with another counter variable.

Who cares?! Well if you wanted to say change the flow of work that Matlab does throughout the loop, you really can’t just assign to the x variable to get it done… you either have to switch loop types or introduce yet another counter (that’s three counters to do a single loop for those keeping score).

Anyway stick to vectors in Matlab if possible! Or save money and get Qt.