Skip to main content
Engineering LibreTexts

3.4.1: for Loop Supplemental Material

  • Page ID
    84377
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    By Carey A. Smith

    Structure of a for loop

    Every for loop must start with the key word "for" followed by the loop index and its values.

    Then the body of the for loop is whatever code your want.

    Then the keyword "end" specifies the end of the loop code.

    This is a simple example:

    for kk = 1:4

    x = cos(kk*pi/16);

    y = sin(kk*pi/16);

    end

    For good style, vertically align the "for" and "end". Indent the body of the for loop.

    You may use the index (kk in this example) in the calculations, as shown in this example. But never modify the loop index inside the for loop. MATLAB will increment the index automatically.

    Watch these videos for additional instruction on for loops:

    Video: Looping structures in MATLAB: Basic FOR loops, Robert Talbert

    Video: MATLAB For Loop Tutorial, Ilya Mikhelson

    Modify Bike_update to round the number of bikes at the end of the day

    The original version of Bike_update.m allows a fraction of a bike to get transferred, which is unrealistic. This modified version rounds the number of bikes, since only whole bikes are transferred.
     

    Example \(\PageIndex{1}\) Bike_loop with whole number of bikes

    The number of bikes transferred is rounded to hole numbers with these lines of code:

    b2c = round(b1*0.05) % Compute the number of bikes that move from B to C
    c2b = round(c1*0.03) % Compute the number of bikes that move from C to B

    Solution

    Add example text here.

     

     

    Exercise \(\PageIndex{1}\) Modified Bike Update for loop with plot

    Create a script named "bike_loop_YourName.m" that uses a for loop to run bike_update.m 30 times. This simulates what would happen during 1 month.

    %% Bike_update (Exercise 2.2)
    % This script models a bike-share system 
    %  with bikes in Boston and Cambridge, Massachusetts
    %
    % Preconditions (Inputs):
    %  Values set before this script is called:
    % b = the number of bikes in Boston (B) at the beginning of the day
    % c = the number of bikes in Cambridge (C) at the end of the day
    %
    % Postconditions (Outputs): 
    %  The values of b and c at the end of the day
    %
    % Algorithm: every day:
    %  5 percent (0.05) of the bikes in Boston are dropped off in Cambridge,
    %  3 percent (0.03) of the bikes in Cambridge get dropped off in Boston. 
    % Use the round function to compute the number of bikes that move each day.
    %
    %% Save the input values, so that they don't change while 
    %  computing the updated values 
    b1 = b; % Save the input value
    c1 = c; % Save the input value
    % Compute the numbers of bikes that move
    b2c = round(b1*0.05) % Compute the number of bikes that move from B to C
    c2b = round(c1*0.03) % Compute the number of bikes that move from C to B
    %% Resulting values:
    b = b1 - b2c + c2b % initial value - those that leave
    %                                  + those that arrive
    c = c1 - c2b + b2c % initial value - those that leave 
    %                                  + those that arrive

     

    --------------------------------------

    Write a script (m-file) that uses a for loop to run bike_update.m 30 times.

    1. Start by clearing any prior variables and scripts:

    clear all; close all; format compact;

    Set b and c to these values:

    b = 100; % Boston, MA

    c = 100; % Cambridge, MA

    2. Open a new figure and plot the numbers of bikes in each location on the first day with this code:

    figure;

    hold on; % This allows us to plot multiple points on one figure.

    plot(0, b, 'b*')  % Plot the number of bikes in Boston at the start with a blue asterisk.

    plot(0, c, 'ro')  % Plot the number of bikes in Cambridge at the start with a red circle.

    grid on;

    % 3. Then put this "for loop" in your code: 

    for k = 1:30
        bike_update
    end

    % Inside the for loop, add this code to plot each day's result: 

        plot(k, b, 'b*')  % Plot the number of bikes in Boston on day k

        plot(k, c, 'ro')  % Plot the number of bikes in Cambridge on day k

    % Add a title to the figure with this code.

    title('Number of Bikes in Boston and Cambridge each day')

    Answer

    Plot of bikes in Boston and Cambridge vs. days

    Add texts here. Do not delete this text first.

    Here are 2 more examples of for loops:

    for loop Factorial flowchart

    Figure \(\PageIndex{i}\): Factorial for loop flowchart
    Factorial Example for loopExample \(\PageIndex{1}\)

    The factorial of a number N in algebra is defined as:

    N! = 1*2*3*...*N

    This can be computed in MATLAB/Octave using a for loop using the logic described in accompanying figure.

    Solution

    The MATLAB code for this is:

    % Input (precondition): N = integer >= 2
    % Output: FN
    FN = 1; % Starting value
    for k = 2:N % k=index, kstart : to kend
        FN = FN*k
    end

     

    Exercise \(\PageIndex{1}\) Compute x^n using a for loop

    Compute x^n these 2 ways:

    1a. Set x = 2

    1b. Set n = 7

    1c. Compute a = x^n.

    2a. Set result = 1

    2b. Code a for loop that multiplies result by x, n times.

    2c. Use this line inside the for loop:

    result = result*x

    Answer

    x = 2 % Initialze x
    n = 7 % Initialze n (the power)
    result = 1 % Initialze the result
    for k=1:n
        result = result*x
    end

    .


    This page titled 3.4.1: for Loop Supplemental Material is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.