Search code examples
matlabmatrixvariable-length

Matrix of unknown length in MATLAB?


I'm trying to set up a zero matrix of variable length with two columns into which I can output the results of a while loop (with the intention of using it to store the step data from Euler's method with adjusted time-steps). The length will be determined by the number of iterations of the loop.

I'm wondering if there's a way I can do this while I'm running the loop or whether I need to set it up to begin with, and how to go about doing that.


Solution

  • if the number of columns is fixed you can always add rows to your matrix (inside the loop)

    e.g.

    while (....)
       .....
       new_row =[x y] ; % new row with values x & y
       mat = [mat ; new_row]; 
    

    of course if you know the number of iterations before the while loop it's more efficient to pre-allocate the matrix