Reputation: 97
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
Reputation: 19689
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.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.
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
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