Reputation: 5690
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?
Upvotes: 2
Views: 7105
Reputation: 12345
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.
Upvotes: 3
Reputation: 32511
Standard syntax is
gazepositionarray(end+1) = [x y]
But you could consider doing something like:
zeros()
)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.
Upvotes: 3
Reputation: 14129
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
Upvotes: 1