Initializing vs growing a structure
Show older comments
I have read the advice on how to avoid inefficient use of memory by preallocation of matrices using zeros for eg. I am having trouble translating that into how to preallocate memory for a structure which has various fields, including some matrices. The structure has to be created a field at a time. But I want to avoid "growing" it and wasting memory.
Could I create a huge array the size of the final structure, and then just start creating structure fields using that matrix name, and avoid thereby duplicate things on the heap while the structure is being built.
If not what is recommended Details appreciated. (Not using Windows, So memory command not available).
Accepted Answer
More Answers (1)
Richard Brown
on 4 Jul 2012
Edited: Richard Brown
on 4 Jul 2012
Let's say you wanted to create a 100x1 struct array with a field A that you know will store a 3x3 matrix
struct('A', repmat({zeros(3)}, 100, 1))
will do the trick.
1 Comment
Dominique
on 13 Sep 2023
Great solution.
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!