help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: For Loop Index Problems


From: Rob Mahurin
Subject: Re: For Loop Index Problems
Date: Thu, 4 Jun 2009 16:33:36 -0400

On Jun 4, 2009, at 2:40 PM, josgau33 wrote:
I am having a simple problem with the for loop and its index. Basically,
here is a simple program to illustrate the problem I am having.

i=1;
a=[1 2 3 8 8 8 3 2 1];

for i=1:length(a)
i
  while a(1,i)==8
  i=i+1;
  i
  end
i
i=i+1;
i
end

This gives the output shown below:
[...]
My question is... Is there any way to avoid the resetting of the index? Is there some sort of for loop where the user is allowed to control the index, and not the computer. If not, can anybody show me modifications to the code that would solve this problem? I cannot seem to figure it out on my own.
Suggestions would be helpful too. Thank you,


Octave's "for" is more like a "foreach" in other languages: at the beginning of each loop the next element from the list is copied into the loop variable. Compare these two one-liners

for i = 1:10; printf("%2d %2d ", i, (i += 3) ); i, endfor
i = 1; while i < 10; printf("%2d %2d ", i, (i += 3) ); i, endwhile

If you want to control the loop variable use a while loop.

Rob

--
Rob Mahurin
Department of Physics and Astronomy
University of Tennessee                 865 207 2594
Knoxville, TN 37996                     address@hidden





reply via email to

[Prev in Thread] Current Thread [Next in Thread]