matlabmatlab-struct

How can I merge redundant fields within a structure?


I have a data set with multiple fields of which several of the fields are different names for equivalent properties. I have rescaled and adjusted the data so that the quantities are comparable and want to merge them into a single field.

As a toy example, let's say I have:

s = struct('pounds', [nan nan 4.8], 'pennies', [120 370 nan]);
s.pennies = s.pennies/100;

How do I merge my incomplete fields to get the desired output:

snew = struct(pounds, [1.2 3.7 4.8]);

Solution

  • If you have modified your field values such that they should be equivalent, and simply need to combine the non-NaN values, one option is to vertically concatenate the fields then use min or max down each column (which will ignore the NaN values). Then just remove the unwanted field with rmfield:

    >> s = struct('pounds', [nan,nan,4.8], 'pennies', [120,370,nan]);
    >> s.pounds = min([s.pounds; s.pennies./100], [], 1);  % Scaling included here
    >> s = rmfield(s, 'pennies')
    
    s = 
    
      struct with fields:
    
        pounds: [1.2000 3.7000 4.8000]