Loop Analysis in MATLAB: What is the Code Doing?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 4K views
gfd43tg
Gold Member
Messages
949
Reaction score
48
Hello,

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

Here is an example code
Code:
A = 0;
while A < 1
    for k=1:5
        A = A+(-1)^k;
    end
    A = A+k;
end

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.
 
Physics news on Phys.org
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?
 
It was an example code problem in the lesson
 
Maylis said:
Hello,

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

Here is an example code
Code:
A = 0;
while A < 1
    for k=1:5
        A = A+(-1)^k;
    end
    A = A+k;
end

<snipped>

I run it and I get 4. I don't understand how this code is working.
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.