## Efficiently Use a Preallocated Array

### Chris (view profile)

on 22 Jun 2011
I’m hoping to make my code more efficient my preallocating my arrays.
I am using matlab to monitor real-time data that I am grabbing from a pipe every 5 seconds or so. It comes into matlab like this:
A =
[7.3468e+005] 'M001' [0.5000]
[7.3468e+005] 'M016' [0.0861]
[7.3468e+005] 'M002' [0.2693]
[7.3468e+005] 'M009' [0.7381]
[7.3468e+005] 'M004' [ 10]
Where A is an (x,3) cell array, with time, the measurement name, and measurement value as the columns.
I take this data and sort it by measurement name into a structure using dynamic field name:
[A_length ~] = size(A);
for xx = 1:1:A_length
data.(A{xx,2}).time = [data.(A{xx,2}).time; A{xx,1}];
data.(A{xx,2}).data = [data.(A{xx,2}).data; A{xx,3}];
end
I also check the length and if it’s > 2500 I truncate to 2300 so that we don’t truncate every time through the loop.
I am thinking of preallocating to see if that’s faster but I’m not sure the best way to do it. Here’s my initial idea:
[A_length ~] = size(A);
for xx = 1:1:A_length
if ~isfield(data,A{xx,2})
data.(A{xx,2}).time = NaN(2500,1);
data.(A{xx,2}).data = NaN(2500,1);
else
data.(A{xx,2}).time = [data.(A{xx,2}).time([2:2499]);A{xx,1}];
data.(A{xx,2}).data = [data.(A{xx,2}).data([2:2499]);A{xx,3}];
end
end
Is there a better way to shift the array (eg to add the data to the end of the arrays)?