matlabvariable-declarationpre-allocation

Declaring a vector in matlab whose size we don't know


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;

Solution

  • 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:

    z = [];
    for ii = 1:x
        z(end+1, 1) = ii; % Index to the (end+1)th position, extending the array
    end
    

    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

    z = [];
    for ii = 1:x
        z = [z; ii];
    end
    

    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

    k = 0;
    while ~condition
        condition = true; % evaluate the condition here
        k = k + 1;
    end
    
    z = zeros( k, 1 ); % now we can pre-allocate
    for ii = 1:k
        z(ii) = ii; % assign values
    end