how to check if two elements are in a row of a matrix?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Pramod Devireddy
am 1 Jul. 2015
Beantwortet: Andrei Bobrov
am 2 Jul. 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   C=[6 9]   which are not present in any row of B.
0 Kommentare
Akzeptierte Antwort
the cyclist
am 2 Jul. 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 Kommentare
Azzi Abdelmalek
am 2 Jul. 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
am 2 Jul. 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.)
Weitere Antworten (2)
Azzi Abdelmalek
am 2 Jul. 2015
Bearbeitet: Azzi Abdelmalek
am 2 Jul. 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')
0 Kommentare
Andrei Bobrov
am 2 Jul. 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,:);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Discrete Math finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!