在Octave中,有这样的矩阵:
abc = [1 2 3; 5 7 8];
def = [5 7 9; 10 11 12];
我想要一个函数,对于abc中的所有[x y z1] s,检查def中是否存在[x y z2],如果存在,则替换它。
所以,我想要像
这样的东西checkandreplace(abc, def);
将abc更改为[1 2 3; 5 7 9]
编辑:
我能想到的最好的是一个循环方案:
for i = 1:size(abc, 1)
index = find(ismember(def(:, [1 2]), abc(i, [1 2]), 'rows'))
if(index)
abc(i, :) = def(index, :)
endif
endfor
能以更好的方式完成吗?
编辑:
忘了添加它应该是稳定的,即它不应该改变abc中行的顺序。
感谢您的帮助!
答案 0 :(得分:1)
您可以通过一次调用ismember
完成整个事情:
[m,I] = ismember(abc(:,1:2), def(:,1:2), 'rows');
abc(m,:) = def(I(m),:);
答案 1 :(得分:0)
它不漂亮,但它有效=)
abc = [1 2 3; 5 7 8];
def = [5 7 9; 10 11 12];
abc(find(ismember(abc(:,1:2),def(:,1:2),'rows')),:) = ...
def(find(ismember(def(:,1:2),abc(:,1:2),'rows')),:)
abc =
1 2 3
5 7 9
如果abc已排序,您可以使用sortrows
对其进行排序。
答案 2 :(得分:0)
这是我的“矢量化”解决方案,没有循环或条件,它应保持原始顺序:
[x y]=find(squeeze(sum(bsxfun(@eq,permute(abc(:,[1 2]), [3 2 1]),def(:,[1 2])),2)==2));
abc(y,:)=def(x,:);
测试:
abc =
1 2 3
5 7 9
它更快吗?你可以测试一下......