Tariq Islam
Tariq Islam

Reputation: 97

Can i change the initially determined max value of the control variable after the loop starts?

In the code maximum value of u is 1(because length of x is 1) at the time of the start of the loop. After calling newftn(), length of x changes. I want my loop to follow the new length of x but it terminates after 1 cycle (i.e. the initial length of x). Please suggest how can I achieve the desired behavior.

x(1) = 1; 
for u = 1:length(x)
    p = 3;
    newftn(); 
end  
function newftn()
    c = [4,5];
    x = horzcat(x,c); 
end

Upvotes: 1

Views: 81

Answers (2)

Sardar Usama
Sardar Usama

Reputation: 19689

  1. You cannot avoid this when using a for loop because once no. of iterations of a for are decided, it cannot be changed later. You can achieve your desired behavior using a while loop.
  2. It is a better practice to pre-allocate memory for a vector instead of growing its size in a loop. e.g. x= zeros(1,n) and then replacing the values.

  3. What you're trying to do here seems like an infinite loop requiring an infinite size of memory. I'm sure this is not what you want! You need to modify your code.

Upvotes: 4

Erfan
Erfan

Reputation: 1927

You can perform this with a while loop instead:

x(1) = 1;
c = [4 , 5];
u = 0;
while u < length(x)
    u = u + 1;
    p = 3;
    x = horzcat(x,c);
end

Upvotes: 1

Related Questions