for Loops


Basic Syntax:

for counter = first : increment : last

    statements   % body of loop
    
end

Examples:

Example 1: roll a die 10 times and report the value on top

for count = 1 : 10
    roll = randi(6);
    disp(['Roll ', num2str(count), ' : ', num2str(roll)]);
end









Example 2: using an increment other than 1

fprintf('*');
for v = 3 : 2 : 11
    fprintf(['-*', num2str(v), '*-']);
end
fprintf('*\n');





Example 3: what is displayed when this code is executed?

for k = 1 : 5
    disp(['k = ', num2str(k)])
    k = 5;
end














Example 4: iterating over a vector

days = ['Mon'; 'Tue'; 'Wed'; 'Thu'; 'Fri'; 'Sat'; 'Sun'];
for order = [7, 2, 4, 1, 3, 5]
    disp(days(order, : ))
end













Example 5: more iterating over a vector

arr = randperm(4);
for k = arr
    disp(['k = ' num2str(k)])
    arr(3) = 9;
end
disp(k)
disp(arr)





Example 6: roll a die 1000 times and count the number of times each side shows up on top

topCount = zeros(1, 6);
for count = 1 : 1000
    top = randperm(6, 1);
    topCount(top) = topCount(top) + 1;
end

fprintf('Face : # times rolled\n')
for k = 1 : 6
    fprintf('%3d  :  %d\n', k, topCount(k))
end