如何合并结构中的冗余字段?

How can I merge redundant fields within a structure?

我有一个包含多个字段的数据集,其中几个字段是等效属性的不同名称。我已经重新缩放和调整了数据,以便数量具有可比性,并希望将它们合并到一个字段中。

举个例子,假设我有:

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

如何合并不完整的字段以获得所需的输出:

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

以下适用于任意数量的字段。由于保证每个位置只有一个字段不NaN,所以可以

  1. 转换为矩阵,使每个原始字段成为矩阵的一行。
  2. 只保留数字,忽略 NaN。根据假设,每列正好给出一个数字。
  3. 将其安排到具有所需字段名称的结构中。

s = struct('pounds',[nan,nan,4.8], 'pennies', [120,370,nan])
s.pennies = s.pennies/100; % example data
target_field = 'pounds'; % field to which the conversion has been done

t = struct2cell(s); % convert struct to cell array
t = vertcat(t{:}); % convert cell array to matrix
t = t(~isnan(t)).'; % keep only numbers, ignoring NaN's
result = struct(target_field, t); % arrange into a struct

如果您修改了字段值以使其等效,并且只需要组合非 NaN 值,一种选择是 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]

试试我下面的两行

c=struct2cell(s);
s=struct('pounds',unique([c{:}]));

更好的是,您还可以使用下面的 oneliner

s=struct('pounds',unique(cell2mat(cellfun(@(x) x(:), struct2cell(s),'UniformOutput',false)))')