This is not something you will see in other programming environments. I came across it some years back and I couldn't understand why it was happening, but after working with MATLAB for some time I was able to figure it out. Look at the code snippet below:
for x = 1:10
for x = 1:10
fprintf('%d,', x);
end
fprintf('\n');
end
you wouldn't expect this to work properly but it does, producing the following output:
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
The reason is that, as with everything else in MATLAB, the x
counter is also a matrix—a vector to be precise. As such, x
is only a reference to an 'array' (a coherent, consecutive memory structure) which is appropriatelly referenced with every consequent loop (nested or not). The fact that the nested loop uses the same identifier makes no difference to how values from that array are referenced. The only problem is that within the nested loop the outer x
is hidden by the nested (local) x
and therefore cannot be referenced. However, the functionality of the nested loop structure remains intact.