How do I initialize an array of unknown dimension?

158 Ansichten (letzte 30 Tage)
Pappu Murthy
Pappu Murthy am 12 Mär. 2018
Bearbeitet: Stephen23 am 12 Mär. 2018
I have a vector whose length is not known apriori. The programs gives a warning with red wiggles underneath indicating that the size of the array varies each loop and preallocating the size is a good idea. But how do I do that since I do not know what is the size going to be.
  1 Kommentar
Geoff Hayes
Geoff Hayes am 12 Mär. 2018
Pappu - do you have an idea of the size of the array? You could pre-allocate to some large size and then reduce the size of the array at the end if there are any "unused" elements.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 12 Mär. 2018
Bearbeitet: Stephen23 am 12 Mär. 2018
"But how do I do that since I do not know what is the size going to be."
You have several main choices:
  • preallocate an array equal to the largest possible size, and then trim it down afterwards.
  • expand the array in blocks/chunks of reasonable size, rather than expanding it one row/column at a time.
  • right click and to tell MATLAB to not show that warning.
  • store the arrays in a preallocated cell array: this is useful if a fixed number of iterations produces an unknown quantity of data.
  • Download and use John D'Errico's excellent FEX submission growdata.
Which one to pick depends on the size of the array, how many times the array size is changed, and what size the changes are each time. The best choice is to implement all three and do a timing comparison. You might like to read this blog:

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by