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.

 采纳的回答

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 个评论

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.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by