MATLAB: Determine total length/size of a structure array with fields as structure arrays

点点圈 提交于 2019-12-10 06:25:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1757250/matlab-determine-total-length-size-of-a-structure-array-with-fields-as-structur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!