필터 지우기
필터 지우기

Pre allocating all fields in a structure?

조회 수: 10 (최근 30일)
HRmatlab
HRmatlab 2016년 8월 26일
댓글: James Tursa 2016년 8월 26일
I have several structures that can have variable sizes and must handle a large amount of data of various types. Each structure may have 25 or more fields. I want to preallocate these structures but all the solutions I found preallocate each structure field individually. pseudo code example:
mystructure.a = preallocate; % using your favorite method
mystructure.b = preallocate;
....
etc.
Since I have so many fields and multiple structures this becomes rather cumbersome. Is there a way to preallocate all the fields in the structure in one line? Example:
mystructure.all the fields = preallocate; % using your favorite method
Thank you in advance
  댓글 수: 2
Stephen23
Stephen23 2016년 8월 26일
편집: Stephen23 2016년 8월 26일
According to Loren's blog post, although it is recommended to preallocate the structure itself, preallocating the contents of each field has no effect on the memory used by the structure.
Essentially the structure is one array (which should be preallocated), but each field is its own array quite independent of the structure itself.
James Tursa
James Tursa 2016년 8월 26일
Expanding a bit on Stephen's comment. Preallocating the structure size and field names makes sense, but preallocating (i.e., assigning values to) the field elements themselves usually only makes sense in two special cases:
1) You want to give a large number of field elements a default value, and you only plan on replacing some of the field elements later on with something different.
2) You plan on altering those field elements essentially "in-place" later on as opposed to replacing them with another variable. E.g., if you are just going to replace them with a different variable later on then the preallocation didn't do anything for you other than slow down your code and use memory unnecessarily.

댓글을 달려면 로그인하십시오.

답변 (1개)

Fangjun Jiang
Fangjun Jiang 2016년 8월 26일
mystructure=cell2struct({1,'xyz'},{'a','b'},2)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by