MATLAB for loop gotcha

Alec Jacobson

April 29, 2014

weblog/

I was surprised by the fact that in MATLAB (at least since version 2013a) running a for over an empty range results in the inner code being executed. I guess the exact definition is that the inner block is executed for each column. So if you have an empty matrix with 10 columns (C = zeros(0,10)) then you'll see 10 block executions. Thus,

C = zeros(0,10);
if isempty(C)
    fprintf('YES C IS EMPTY\n');
end
for foo = C
  fprintf('WHAT!\n');
end