how to check if two elements are in a row of a matrix?

7 次查看(过去 30 天)
suppose
A=[1 2;
4 5;
6 9]
B=[1 3 5 6;
1 2 4 7;
5 6 4 8;
1 2 3 4].
In this case 1,2 of 1st row of A are present in 2nd row B, similarly all rows of A have to check with rows of B, and create a matrix &nbsp C=[6 9] &nbsp which are not present in any row of B.

采纳的回答

the cyclist
the cyclist 2015-7-2
Here is one clumsy way:
A=[1 2;
4 5;
6 9];
B=[1 3 5 6;
1 2 4 7;
5 6 4 8;
1 2 3 4];
rowCountA = size(A,1);
rowCountB = size(B,1);
this_row_of_A_is_in_B = false(rowCountA,1);
for nb = 1:rowCountB
this_row_of_A_is_in_B = this_row_of_A_is_in_B | all(ismember(A,B(nb,:)),2);
end
rows_of_A_that_are_not_in_B = A(not(this_row_of_A_is_in_B),:)
  2 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2015-7-2
This doesn't work for this example
A=[1 2;
4 5;
6 9
1 8]
B=[1 3 5 6;
1 2 4 7;
5 6 4 8;
1 2 3 4]
the cyclist
the cyclist 2015-7-2
By my understanding of the problem, the output for these inputs should be
[6 9;
1 8]
because there is no row of B that has [6,9] and also no row that has [1,8].
That output is what my code has, so it behaves as I intended, and how I interpreted the question. (But, of course, I could be interpreting incorrectly.)

请先登录,再进行评论。

更多回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2015-7-2
编辑:Azzi Abdelmalek 2015-7-2
A=[1 2;
4 5;
6 9
1 8]
B=[1 3 5 6;
1 2 4 7;
5 6 4 8;
1 2 3 4]
out=[];
for ii=1:size(A,1)
for jj=1:size(B,1)
id=all(ismember(A(ii,:),B(jj,:)));
if id==1
out(end+1,:)=A(ii,:);
break
end
end
end
out=setdiff(A,out,'rows')

Andrei Bobrov
Andrei Bobrov 2015-7-2
ii = fullfact([size(A,1),size(B,1)]);
t = arrayfun(@(i1)sum(ismember(B(ii(i1,2),:),A(ii(i1,1),:))),(1:size(ii,1))') < 2;
C = A(accumarray(ii(:,1),t) == 4,:);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by