value of for loop increases without even executing all the lines inside the loop

hi,
my code is as follows-
for i=1:large_rand_number
number_of_iterations= 2^(i-1);
gamma_element=zeros(2,number_of_iterations)
for j= 1: number_of_iterations
bisection; %this produces a 2x1 matrix each time
gamma_element(:,j)=gamma
end
if i==1
bisection_points=gamma_element;
else
bisection_points=[gamma_element(:,1),reshape([bisection_points;gamma_element(:,[2:end])],size(bisection_points,1),[])];
end
...
...
...
end
now, when i=1, it executes the j-loop for once. and as soon as it exits the j-loop, the value of i=2, even though there are many more lines including a few shown here. so under the if-else condition, it never fulfils
if i==1
bisection_points=gamma_element;
rather fulfils the else condition.
can anyone tell me why value of i is incremented without executing all lines inside the i-loop.

2 Comments

@Muhammad Ridwanur Rahim: please upload your actual code by clicking the paperclip button.

Sign in to comment.

 Accepted Answer

You call some scripts, e.g. bisection, which redefine i.
This is a classic example of why using functions is much better than using scripts. Scripts are fun for playing around with, but should not be used if you want reliable, repeatable, robust code.

3 Comments

thnx, you might be right. changed from i to ii in this code.
This is one of many reasons why you should use functions rather than call scripts from inside other scripts or functions. It is almost impossible to keep track of your workspace and what might be changing when you do that.
@Muhammad Ridwanur Rahim: changing i to ii just creates another bug in the future... the real solution is to use a function, and avoid this problem entirely.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!