一种方法是识别唯一行unique
,然后使用一些逻辑索引来组合它们的数据速率。
例如:
% Sample Data
temp_links = struct('src',{'sw_1', 'sw_1', 'sw_1', 'sw_2', 'sw_2', 'sw_2'}, ...
'dest',{'sw_2', 'sw_2', 'sw_3', 'sw_1', 'dev_1', 'dev_1'}, ...
'type', {'sw', 'sw', 'sw', 'sw', 'dev', 'dev'}, ...
'datarate', {23, 34, 2, 5, 5, 5} ...
);
% Locate and index each unique source, destination, and type
[src_nodes, ~, src_idx] = unique({temp_links(:).src});
[dest_nodes, ~, dest_idx] = unique({temp_links(:).dest});
[types, ~, type_idx] = unique({temp_links(:).type});
% Combine the indices and use to locate and index unique rows
row_layout = [src_idx, dest_idx, type_idx];
[unique_rows, ~, row_idx] = unique(row_layout, 'rows');
% Initialize results table based on the unique rows
joined_links = struct('src', {src_nodes{unique_rows(:,1)}}, ...
'dest', {dest_nodes{unique_rows(:,2)}}, ...
'type', {types{unique_rows(:,3)}}, ...
'datarate', [] ...
);
% Sum data rates for identical rows
for ii = 1:size(unique_rows, 1)
joined_links(ii).datarate = sum([temp_links(row_idx==ii).datarate]);
end
对于我们的示例输入结构:
src dest type datarate
______ _______ _____ ________
'sw_1' 'sw_2' 'sw' 23
'sw_1' 'sw_2' 'sw' 34
'sw_1' 'sw_3' 'sw' 2
'sw_2' 'sw_1' 'sw' 5
'sw_2' 'dev_1' 'dev' 5
'sw_2' 'dev_1' 'dev' 5
我们收到以下连接结构:
src dest type datarate
______ _______ _____ ________
'sw_1' 'sw_2' 'sw' 57
'sw_1' 'sw_3' 'sw' 2
'sw_2' 'dev_1' 'dev' 10
'sw_2' 'sw_1' 'sw' 5
或者,如果您想使用 MATLAB 的Table
数据类型,您可以更轻松地使用findgroups
并splitapply
获得相同的结果。
使用上面的相同temp_links
结构:
temp_links = struct2table(temp_links);
groups = findgroups(temp_links.src, temp_links.dest, temp_links.type);
combined_datarate = splitapply(@sum, temp_links.datarate, groups);
[unique_groups, idx] = unique(groups);
joined_links = temp_links(idx, :);
joined_links.datarate = combined_datarate;
这也返回:
src dest type datarate
______ _______ _____ ________
'sw_1' 'sw_2' 'sw' 57
'sw_1' 'sw_3' 'sw' 2
'sw_2' 'dev_1' 'dev' 10
'sw_2' 'sw_1' 'sw' 5