两个矩阵的联合及其共同属性在matlab中加在一起

时间:2017-04-28 16:19:34

标签: matlab matrix union

我有两个结构,我希望有两个矩阵的联合,而第三行是根据共同的前两行添加的,结果对于第一个拖曳行是顺序不敏感的,避免重复值。即

% struct1
row1 = [1  1  1  2  4  3];
col1 = [1  2  3  1  2  4];
att1 = [2  3  4  6  2  5];
% struct2
row2 = [2  2  1  3  3];
col2 = [1  2  3  1  4];
att2 = [1  0  1  1  5];
% result
resultRow = [1 1 1 2 2 3]
resultCol = [1 2 3 2 4 4]
resultAtt = [2 10 6 0 2 10]

我之前被问过the intersection of two structure但似乎accumarray适用于行而不是矩阵。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

根据这个问题intersection部分的解决方案,我认为我们可以按以下步骤进行:

% struct1
row1 = [1  1  1  2  4  3];
col1 = [1  2  3  1  2  4];
att1 = [2  3  4  6  2  5];
% struct2
row2 = [2  2  1  3  3];
col2 = [1  2  3  1  4];
att2 = [1  0  1  1  5];
% sort in 2nd dimension to get row-column indexes insensitive for order
idx1 = sort([row1(:) col1(:)],2);
idx2 = sort([row2(:) col2(:)],2);
%find union
[idx,~,bins] = unique([idx1;idx2],'rows','stable');
att = accumarray(bins,[att1,att2]);
ResultUnion= [idx att]';
disp(ResultUnion)

你得到了

ResultUnion =

     1     1     1     2     3     2
     1     2     3     4     4     2
     2    10     6     2    10     0