Q&A
Ask and answer questions to make information more available to wider audiences.
Melanie Leavit @leavitmelanie   22, Aug 2023 12:00 AM
foreach
Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?
answers 1
 
Answer 1
Drake Boot @bootdrake85   31, Aug 2023 03:20 PM
MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.

A = 1:5;

for i = A
    A = B;
    disp(i);
end

If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate, you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:

n = 10;
f = n;
while n > 1
    n = n-1;
    f = f*n;
end
disp(['n! = ' num2str(f)])