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

8 vues (au cours des 30 derniers jours)
Pramod Devireddy
Pramod Devireddy le 1 Juil 2015
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.

Réponse acceptée

the cyclist
the cyclist le 2 Juil 2015
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 commentaires
Azzi Abdelmalek
Azzi Abdelmalek le 2 Juil 2015
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 le 2 Juil 2015
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.)

Connectez-vous pour commenter.

Plus de réponses (2)

Azzi Abdelmalek
Azzi Abdelmalek le 2 Juil 2015
Modifié(e) : Azzi Abdelmalek le 2 Juil 2015
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 le 2 Juil 2015
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,:);

Catégories

En savoir plus sur Discrete Math dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by