Stuart’s MATLAB Videos

Watch and Learn

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

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

Posted by Doug Hull,

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.

Note

Comments are closed.

2 CommentsOldest to Newest

Paulo Silva replied on : 1 of 2
Hi Dough, another nice video tutorial. The mat array should be preallocated first don't you agree?
dhull replied on : 2 of 2
@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