在matlab中搜索a结构的并行行以查找公共项
我已存储了的(行、列、值)信息在matlab中搜索a结构的并行行以查找公共项,matlab,search,key,indices,Matlab,Search,Key,Indices,我已存储了的(行、列、值)信息 key1: (1,1) (1,2) (1,3) (4,2) (3,4) attribute1: 2 3 4 2 5 详情如下: Structure A1: key row1: 1 1 1 4 3 key col1: 1 2 3 2 4 attribute1: 2 3 4 2 5 类似地,对于结构A2 Structure A2: k
key1: (1,1) (1,2) (1,3) (4,2) (3,4)
attribute1: 2 3 4 2 5
详情如下:
Structure A1:
key row1: 1 1 1 4 3
key col1: 1 2 3 2 4
attribute1: 2 3 4 2 5
类似地,对于结构A2
Structure A2:
key row2: 2 2 1 3
key col2: 1 2 3 4
attribute2: 1 0 1 5
现在,我希望能够同时在结构A1和A2之间的行和列键项中搜索公共条目。这在概念上是find[common_item,index]=intersect([row2,col2],[row1,col1])。我希望最终结果对行和列的顺序不敏感。因此,在我的示例中,(1,2)键值等于(2,1)值。然后,公共条目的属性值应该加在一起。预期的结果是
Structure Result: //it recognizes (1,2) and(2,1) are the same.
key row: 2 1 3
key col: 1 3 4
attribute: 4 5 10
我应该如何继续搜索常见条目并执行一些操作ismember
函数可以搜索一行中的常用项,如果有多次出现,则只计算第一个。此外,正如我所说,我希望它在键值中不区分顺序
感谢您的帮助。首先使用
排序
实现行-列顺序不敏感,然后使用唯一
处理每个结构中的行-列重复,最后使用ismember
(使用'rows'
)查找结构之间的公共键。请注意,我在每个结构中添加了一个内部副本,以显示第二阶段效果:
% 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);
% search for duplicates inside each struct
[idx1,~,bins1] = unique(idx1,'rows','stable');
att1 = accumarray(bins1,att1);
[idx2,~,bins2] = unique(idx2,'rows','stable');
att2 = accumarray(bins2,att2);
% search common entries
common1 = ismember(idx1,idx2,'rows');
row = idx1(common1,1);
col = idx1(common1,2);
common2 = ismember(idx2,[row col],'rows');
% add common values
att = att1(common1) + att2(common2);
Result.row = row';
Result.col = col';
Result.attribute = att';
disp(Result)
你会得到:
Result =
row: [1 1 3]
col: [2 3 4]
attribute: [10 6 10]
了不起的非常感谢@user2999345的详细回答:)亲爱的@user2999345,如果我们要找到两个结构的并集,而公共项添加了属性值,那么我们应该在代码的其余部分使用并集函数吗?问题是