Remove specific field and "push up" its contents without losing the data.

I am loading a structure into MatLab and I would like to remove a field without losing the contents of that field. I'll explain exactly what I mean nowsince that may be confusing.
After loading the structure
Data.c1 = load(Data.mat);
The output is
Data.c1.Data.sN; % where I have 1-N "s" fields
I want to effectively convert this to
Data.c1.sN; % "pushing up" the "s" fields from 1-N
All the data within the lowest "s" fields would be moved up and take the place of the field Data in the variable Data.
Is there an easy way to do that?

 Accepted Answer

Looks like something as simple as this works.
A = struct2cell(Data);
B = A{1};
C = B.Data.s;
Data.c1 = C;

More Answers (1)

temp = rmfield(Data.c1, 'Data');
fn_temp = fieldnames(Data.c1);
fn_c1D = fieldnames(Data.c1.Data);
combined_cell = [struct2cell(fn_temp); struct2cell(Data.c1.Data)];
combined_fn = [fn_temp;fn_c1D];
Data.c1 = cell2struct(combined_cell, combined_fn);
Obviously test this first !!

6 Comments

I'm getting this error when I run it.
Undefined function 'struct2cell' for input arguments of type 'cell'.
combined_cell = [struct2cell(fn_temp); struct2cell(Data.c1.Data)];
Isn't struct2cell a built in MatLab function though?
I saw you deleted a comment about replacing fn_temp with temp, and that gave this error.
Error using cell2struct
Number of field names must match number of fields in new structure.
Any other ideas?
It might have to do with my combined cell being a 1 x 1 cell containing a size 1 x 10 struct and how temp is empty.
When I change temp back to fn_temp this is the error I get.
Check for incorrect argument data type or missing argument in call to function 'struct2cell'.
If temp is empty, the implication is that Data.c1.Data is the only field within Data.c1 . In such a case, the code becomes very simple:
Data.c1 = data.c1.Data;
The longer code I had was based upon the idea that you had additional Data.c1.* fields that needed to be preserved.
I do have those fields. Maybe I missed something in the original files when I asked the question but they are all of the form Data.c1.Data.sN.
If you use
fieldnames(Data.c1)
then does anything other than Data show up ?

Sign in to comment.

Categories

Products

Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!