2

I am running a solution on an eye tracking system at 1000Hz. Data comes in from the eye tracker in the form of a X and Y gaze position co-ordinate. I am trying to add these two co-ordinates to the end of an array as they come in.

My current solution is as follows:

gazePositionArray = [];    
while gazeDataIsAvailable
    [x y] = getNewCoordinates;
    gazePositionArray = [gazePositionArray; x y];
end

The problem lies in the fourth line. In order for the array to update, it copies the contents of the old array and adds the new co-ordinates on the end. This is fine, for example, for the first 30 seconds of recording, but the more data exists in the array, the more processing the computer has to do in order to create the new array (after 30 seconds the system is trying to copy 30,000 lines of data 1000 times per second - with this getting more and more at each iteration)

Is there a way to append a row to the end of a MATLAB array without the system having to copy the whole array into itself?

CaptainProg
  • 5,610
  • 23
  • 71
  • 116

3 Answers3

3

Standard syntax is

gazepositionarray(end+1) = [x y]

But you could consider doing something like:

  • Allocate space for an initial array (zeros())
  • Keep a variable for max index used
  • Each time hit the array limit, copy to an array that's double the size.

This way you'll only copy log_2 n times (e.g. 19 times vs 1 million times if you have a million elements). At the end you can chop out the part that's unused.

YXD
  • 31,741
  • 15
  • 75
  • 115
3

Some related questions:

Matrix of unknown length in MATLAB?

Pre-allocating memory in MATLAB à la std::vector::reserve(n).


The typical solution is to preallocate a "big" piece of memory, and the smartly copy to a bigger piece of memory when needed. My favorite is to double the size whenever the current allocation become full, but there are others.

None are hard, but they all require a few extra lines of code. See the questions and answer above for some examples.

Community
  • 1
  • 1
Pursuit
  • 12,285
  • 1
  • 25
  • 41
1

You have to preallocate the memory.

gazePositionArray = zeros(30000,2);
counter = 1;    
while gazeDataIsAvailable
    [x y] = getNewCoordinates;
    gazePositionArray(counter,:) = [x y];
    counter = counter + 1;
end
Lucas
  • 13,679
  • 13
  • 62
  • 94
  • The 30 seconds was just an example; it could run to several minutes! But that's useful to know, thanks – CaptainProg Feb 14 '12 at 15:44
  • @CaptainProg: Ideally you have an idea of how much memory you need, then no reallocation is necessary. If that is not the case you should always reallocate a big chunk. Generally it is best to double the size of allocated memory each time you need new memory. Mr E only changed the syntax, I don't think this will give you any speed improvement unless MATLAB does something clever that I am not aware of in that case. – Lucas Feb 14 '12 at 15:50