Doug's MATLAB Video Tutorials

March 9th, 2011

How to store a series of vectors from a for loop.

A very common question among new MATLAB users is how to store the results of a calculation done in a for loop. I covered how to do this when the result is a scalar However, I did not cover how to do this if you are creating a vector each time through the loop.

I often see people try to store the results in a series of vectors with names like alpha1, alpha2, alpha3… This is not a good idea, it is hard to manipulate and refer to these variables. Better is to store each resultant vector as a row in a larger matrix.

2 Responses to “How to store a series of vectors from a for loop.”

  1. Paulo Silva replied on :

    Hi Dough, another nice video tutorial.

    The mat array should be preallocated first don’t you agree?

  2. dhull replied on :

    @Paulo

    It depends. The point of my videos is to illustrate a concept clearly an concisely. Pre-allocation would be marginally better in a situation like this, but because the matrices are small it would be only a small improvement.

    In real code, I would totally pre-allocate if this was a matrix of any real size, but for small ones I might or might not do it. I prefer clarity and brevity most of the time. If speed becomes an issue later, I can easily add that optimization.

    Thanks for asking,
    Doug


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of MathWorks.