Debugging: My Unexpected Result of n1=75

  • Thread starter Thread starter hokhani
  • Start date Start date
  • Tags Tags
    Debugging
Click For Summary
SUMMARY

The discussion centers on a MATLAB code snippet that produces an unexpected result of n1=75 instead of the anticipated n1=25. The code consists of nested loops where the inner loop sums the values of m from 1 to 5, resulting in a total of 15 for each iteration of the outer loop, which runs 5 times. To achieve the desired output of 25, the user should modify the inner loop to increment n1 by 1 instead of summing m.

PREREQUISITES
  • Understanding of MATLAB programming syntax
  • Familiarity with nested loops in programming
  • Basic knowledge of arithmetic operations in MATLAB
  • Ability to debug and analyze code outputs
NEXT STEPS
  • Review MATLAB loop structures and their implications on variable values
  • Learn about debugging techniques in MATLAB to identify logical errors
  • Explore MATLAB's built-in functions for summation and iteration
  • Practice writing and modifying nested loops in MATLAB for different outcomes
USEFUL FOR

This discussion is beneficial for MATLAB programmers, educators teaching programming concepts, and anyone interested in debugging code logic and understanding loop behavior in programming.

hokhani
Messages
601
Reaction score
22
The program below gives the result n1=75 wheras I expect to get n1=25. What is my mistake?

[C O D E]
clc
clear all
n1=0;
for n=1:5
for m=1:5
n1=n1+m;
end
end
n1
[/C O D E]
 
Physics news on Phys.org
Code:
clc
clear all
n1=0;
for n=1:5
    for m=1:5
        n1=n1+m;
    end
end
n1

The inner loop (for m=1:5) adds 15 to the value of n1. The outer loop (for n=1:5) tells it to do that 5 times. Therefore you get 75.
 
  • Like
Likes   Reactions: hokhani
If you want 25 you should do n1=n1+1 instead.
 
  • Like
Likes   Reactions: hokhani

Similar threads

  • · Replies 4 ·
Replies
4
Views
24K
  • · Replies 10 ·
Replies
10
Views
4K
  • · Replies 2 ·
Replies
2
Views
5K
Replies
12
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
7K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K