Matlab Object Array Efficiency

For my work, I have to create a project in Matlab, which is not my language of choice, and I have some questions regarding efficiency.

I am currently dealing with a set of points with several properties. Instead of putting all this into separate arrays of equal length, I would prefer to make a single array of Point objects using classes defined by the Matlab user. For example:

% Point.m classmethod Point < handle properties x, y, prop1, prop2 end end % script.m ... % define x(100), y(100), prop1(100), prop2(100) points(100) = Point; % this seems to be the way to allocate an object vector for i = 1:100 points(i).x = x(i); % copy values into object points(i).y = y(i); points(i).prop1 = prop1(i); points(i).prop2 = prop2(i); end 

The reason I prefer the above is both aesthetic (objects must be objects) and practical, because it makes it easy to create subsets of points without the need to index several different arrays.

However, I wonder if this is the most effective way to do something, given that many points can grow quite large in the amount of thousands or tens of thousands of points. My main questions are:

  • For my understanding: how does Matlab store arrays of objects in memory? How does it handle the various sizes of an object depending on prop1, for example, struct?
  • How does this affect operations such as [points.x], something that I will need to do quite often? Is this an effective operation?
  • Is there a better way to initialize an array of objects? The above loop design seems extremely inefficient.
  • I suggest that it should be possible to model the behavior of an object while maintaining properties more favorably, possibly by overloading subsref . Would you recommend this?

Or put things more general: what would be the best way to organize my points?

Waiting for your advice!

+6
performance object matlab
source share
1 answer

I do not answer your questions in order, but here are some, I hope, useful information:

  • Objects are stored in memory in the same way as structures - each field is its own full-blown MATLAB array (mxArray for C-Mex programmers), so the size of each field can be independent.
  • I would probably do something like a single PointList with fields x, y, prop1, prop2. Then these fields will be vectors of the corresponding length. This will almost certainly be more efficient than a list of Point objects. It will certainly take less memory.
  • You must define access methods in PointList to ensure that your vectors always have the same length, etc.
  • If you really wanted to, you could have your PointList potential, which is greater than the number of elements that are currently stored in it. This way you can avoid resizing x, y, ... all the time
  • In general, subsref overload is not for the faint of heart. Keep in mind that you also need to correctly overload at least the number, ndims, length, end and size.
+9
source share

All Articles