Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Loops Analysis (MATLAB)

  1. Jun 20, 2014 #1


    User Avatar
    Gold Member


    I am trying to decipher loop codes and I am having a lot of difficulty doing so

    Here is an example code
    Code (Text):
    A = 0;
    while A < 1
        for k=1:5
            A = A+(-1)^k;
        A = A+k;
    So I thought the while function does something an infinite amount of times. This is what I think this code is doing

    It starts with A = 0, (not sure what the while A < 1 is doing), then the for statement does this

    A = 0 + (-1)^1 = -1
    A = -1 + 1 = 0

    for k = 1, then it must repeat this statement (k=2). The A = 0 in this line is not from the first line of code, it comes from the result for k=1,
    A = 0 + (-1)^2 = 1
    A = 1 + 2 = 3

    well I guess somewhere here the A < 1 is violated, thus the code should stop? I run it and I get 4. I don't understand how this code is working.
  2. jcsd
  3. Jun 20, 2014 #2


    Staff: Mentor

    This code is pretty much nonsensical and can be simplified:

    the for k=1:5 loop

    A = A -1 + 1 -1 +1 -1

    which basically subtracts one from A which means the outer while loop will run forever except

    the statement A = A + k is outside the loop and so k is undefined at this point ie you should get a compile error

    Where did you get this code?
  4. Jun 20, 2014 #3


    User Avatar
    Gold Member

    It was an example code problem in the lesson
  5. Jun 20, 2014 #4


    User Avatar
    Gold Member

    Step through it line by line and you can see how it gets a result of 4.

    1. A = 0.
    2. while A<1 is true, so continue.
    3. Enter the for loop, and start with k=1.
    4. A =-1
    5. now k=2.
    6. A = 0
    7. now k=3.
    8. A = -1
    9. now k=4.
    10. A = 0
    11. now k=5, the last time through the for loop.
    12. A =-1.
    13. A = A+k, so A = -1+5 = 4.
    14. Check if A<1. It evaluates to false so exit the while loop.
    15. Return the answer of 4.

    Basically, a while loop executes as long as the condition is true. In this case, it executes as long as A<1 is true.

    A for loop executes for each specified value. So for k=1:5 means the loop executes for each separate value of k. Notice that the A=A+k line doesn't execute until the for loop is completely done.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook