Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change for loop index variable inside the loop

I need to change my loop variable inside the iteration as I have to access array elements in the loop which is changing w.r.t size inside the loop.

Here is my code snippet:

que=[];
que=[2,3,4];
global len;
len=size(que,2)
x=4;
for i=1:len 
    if x<=10
    que(x)= 5;
    len=size(que,2)
    x=x+1;

    end
end
que

Array should print like:

2 3 4 5 5 5 5 5 5 5 

But it is printed like this:

2 3 4 5 5 5

In Visual C++ the array is calculated correctly and whole array of 10 elements is printed, which increases at run time.

How can I accomplish this in Matlab?

like image 589
shawana Avatar asked May 14 '10 05:05

shawana


People also ask

Can you change i inside a for loop?

A for loop assigns a variable (in this case i ) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i will become the next element. The while loop has no such restriction.

What is loop index in for loop?

An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.

What is a loop index variable?

The loop variable defines the loop index value for each iteration. You set it in the first line of a parfor statement. parfor p=1:12. For values across all iterations, the loop variable must evaluate to ascending consecutive integers. Each iteration is independent of all others, and each has its own loop index value.


1 Answers

You should use a while loop instead of a for loop to do this:

que = [2 3 4];
x = 4;
while x <= 10
  que(x) = 5;
  x = x+1;
end

Or, you can avoid using loops altogether by vectorizing your code in one of the following ways:

que = [2 3 4];             %# Your initial vector
%# Option #1:
que = [que 5.*ones(1,7)];  %# Append seven fives to the end of que
%# Option #2:
que(4:10) = 5;             %# Expand que using indexing
like image 114
gnovice Avatar answered Oct 15 '22 05:10

gnovice