MATLAB: How can you move up data in a structure to a higher level

organizationstructures

Hi all,
I was given a dataset that has 3 "levels" in the structure. One of the levels is redundant and I'm very sick of typing it. However, there's a lot of data in this structure and it would take me forever to rename individually.
Basically I have a structure like this:
Data (structure name)->Data 1, Data 2, Data 3, etc(1 level down, each Data here corresponds to a different research subject)-> Data (2 levels down)-> 50 variables (3rd level down).
Basically, I want to remove the 2nd 'Data' level because it adds no organization or information, and certain aspects of my code are ridiculously long because of it. I tried to just delete the 2nd data with a right click delete, of course that got rid of all the variables under it… which is all of them for Data 1, Data 2 etc. Even with a for loop for renaming all the data, I would have to have all 50 variables renamed just to run through each of the separated data.
Is there any easy way to just bump up the level that variables are on?

Best Answer

First thing, let's convert all the dataxxx scalar structure into a structure array. The simplest way is to convert your upper level structure into a cell array (very fast) then concatenate all the cells which will form a structure array:
datacell = struct2cell(yourmainstructure);
dataarray = [data{:}];
So now, you should have a 1xNumber of animals structure with 1 useless Data field that is itself a structure that contain the useful data. To get rid of that extra level of indirection, again convert to a cell array (it should create a 1x1xNumer of animals cell array) and concatenate
datacell = struct2cell(dataarray);
dataarray = [datacell{:}];
This should result in a 1xNumber of animals structure with 50 fields. Easy to index.
And of course, you should fix whatever code generated that unnecessary complicated hierarchy in the firt place.