views:

1554

answers:

1

I have a structure array containing fields as structure arrays of varying length. For example:

's' is a structure 'data' is a field in 's', and also a structure array itself and

length(s(n).data) ~= length(s(m).data)

I want to preallocate an array that takes a time stamp from every field s.data.timestamp. Is there a way to do this without using a for loop twice? This is what I have so far:

% find the total length
count=0;
for x=1:length(s)
  count=count+length(s(x).data);
end
% preallocate timestamp array
timestamp=zeros(1,count);
% populate timestamp array
index=1;
for x=1:length(s)
   for y=1:length(s(x).data)
      timestamp(index)=s(x).data(y).timestamp;
      index=index+1;
   end
end

I thought about just overestimating the length that I would need based on the length of 's' and an average length of 'data', but the actual length of each 'data' field/substructure varies widely. Would I be better off just overestimating the heck out of it and trimming the resulting array afterward? Zero timestamps are impossible with the data set I'm working with, so that shouldn't be a problem.

+5  A: 

This will work if every structure array data has the same fields and are row vectors (i.e. 1-by-N):

allData = [s.data];               %# Concatenate all data arrays into one
timestamp = [allData.timestamp];  %# Collect all the time stamps

If the data structure arrays are column vectors (i.e. N-by-1), you need to use VERTCAT instead:

allData = vertcat(s.data);        %# Concatenate all data arrays into one
timestamp = [allData.timestamp];  %# Collect all the time stamps

The above solutions work due to the fact that accessing a single field of a structure array returns a comma-separated list.

gnovice
Wow! Only two lines - I believe the term "freakin' genius" may apply here.
Doresoom
@doresoom: Comma-separated lists are your friends. ;)
gnovice