Effective indexing of structures in MATLAB

Until recently, I saved time series data in a struct in MATLAB, placing the index after the field name, for example:

 Structure.fieldA(1) = 23423 

So, the structure has a set of fields, and each field is a vector.

I saw how many other programs use a different format, where the structure itself is indexed and each structure index contains a set of fields, for example:

 Structure(1).fieldA 

What is the most effective method? Should I stick to the top option or should I switch my programs to using the bottom method?

+5
source share
1 answer

A struct , where each field is an array, is more effective because you have fewer data elements (one array per field), while a struct array has more flexibility due to performance and memory usage (per per struct element per field).

From MATLAB

Structures require the same amount of overhead for each field. Structures with many fields and small contents have large overheads and should be avoided. A large array of structures with numerical scalar fields requires much more memory than a structure with fields containing large numerical arrays.

We can check the memory usage with a simple example.

 S = struct('field1', {1, 2}, 'field2', {3, 4}); SArray = struct('field1', {[1,2]}, 'field2', {[3,4]}); whos S* % Name Size Bytes Class Attributes % % S 1x2 608 struct % SArray 1x1 384 struct 

Some of the flexibility provided by the struct array includes the ability to easily capture a subset of the data:

 subset = SArray(1:3); % Compared to subset.field1 = S.field1(1:3); subset.field2 = S.field2(1:3); 

In addition, the ability to store data of different sizes, which may not easily fit into an array.

 S(1).field1 = [1,2]; S(2).field1 = 3; 

Which solution is better really depends on the data and how you use it. If you have a large amount of data, the first option is likely to be preferable due to less memory.

If you work with code, I would not worry about converting it just for the sake of using another convention, if you have no performance problems (in this case, use struct arrays) or difficulties accessing / modifying data (use a struct array).

+5
source

Source: https://habr.com/ru/post/1263541/


All Articles