我有一个n-by-3矩阵。像这样:
mtx = [3 1 3;
2 2 3;
2 3 2;
5 4 1]
我希望最终结果是:
mtx2 = [0 0 0;
2 2 3;
2 3 2;
0 0 0]
所以我想在没有第一个数字的行上加零,并且他们的第二个数字不等于另一个数字的第三个数字。
想象一下,任何一行的第一个数字是' a',第二个''和第三个' c'。对于第1行,我会对它进行比较' a'和其他所有人一样。如果没有另一个' a'等于那,然后第1行变为[0 0 0]。但如果还有另一个' a'等于那个,对于第2行的瞬间,我将比较' b' #1和' c' #2。如果它们相等则这些行保持不变。如果不是第1行变为[0 0 0]。等等。
答案 0 :(得分:2)
看看这是否适合你 -
%// Logical masks of matches satisfying condition - 1 and 2
cond1_matches = bsxfun(@eq,mtx(:,1),mtx(:,1).') %//'
cond2_matches = bsxfun(@eq,mtx(:,3),mtx(:,2).') %//'
%// Create output variable as copy of input and use the conditions to set
%// rows that satisfy both conditions as all zeros
mtx2 = mtx;
mtx2(~any( cond1_matches & cond2_matches ,1),:)=0
答案 1 :(得分:0)
我通过这种方式搜索,针对每一行测试你的两个标准。
Izeros=[]; % here is where I'll store the rows that I'll zero later
for Irow = 1:size(mtx,1) %step through each row
%find rows where the first element matches
I=find(mtx(:,1)==mtx(Irow,1));
%keep only those matches that are NOT this row
J=find(I ~= Irow);
% are there any that meet this requirement
if ~isempty(J)
%there are some that meet this requirement. Keep testing.
%now apply your second check, does the 2nd element
%match any other row's third element?
I=find(mtx(:,3)==mtx(Irow,2));
%keep only those matches that are NOT this row
J=find(I ~= Irow);
% are there any that meet this 2nd requirement
if ~isempty(J)
%there are some that meet this 2nd requirement.
% no action.
else
%there are none that meet this 2nd requirement.
% zero the row.
Izeros(end+1) = Irow;
end
else
%there are none that meet the first requirement.
% zero the row.
Izeros(end+1) = Irow;
end
end