MATLAB Loop Analysis in MATLAB: What is the Code Doing?

AI Thread Summary
The discussion focuses on understanding a MATLAB code snippet involving nested loops. The code initializes A to 0 and uses a while loop that continues as long as A is less than 1. Inside the while loop, a for loop iterates from 1 to 5, modifying A based on the expression A + (-1)^k. After the for loop, A is incremented by the final value of k, resulting in A equaling 4 when the while loop condition is checked again. The explanation clarifies that the while loop executes until A is no longer less than 1, demonstrating the code's functionality.
gfd43tg
Gold Member
Messages
947
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.
 

Similar threads

Back
Top