Suppose we are running an infinite for loop in MATLAB, and we want to store the iterative values in a vector. How can we declare the vector without knowing the size of it?
z=??
for i=1:inf
z(i,1)=i;
if(condition)%%condition is met then break out of the loop
break;
end;
end;
Please note first that this is bad practise, and you should preallocate where possible.
That being said, using the
end
keyword is the best option for extending arrays by a single element:You can also concatenate results from previous iterations, this tends to be slower since you have the assignment variable on both sides of the equals operator
Sadar commented that directly indexing out of bounds (as other answers are suggesting) is depreciated by MathWorks, I'm not sure on a source for this.
If your
condition
computation is separate from the output computation, you could get the required size first