Does something similar to 'intersect' command exists for more than 2 vectors?
조회 수: 35 (최근 30일)
이전 댓글 표시
Hi,
There are 5 row vectors with different(or same) number of elements. The problem is to pick out the 'intersecting' elements from these 5 vectors.
'intersect(A,B)' works with only 2 vectors. Is there a command/procedure for more than 2 vectors?
Thanks.
댓글 수: 0
채택된 답변
Matt Fig
2011년 6월 5일
You could call INTERSECT multiple times:
A = [1 2 3 4 5];B = [3 7 8 9 5];C = [5 0 22 3 77];
F = intersect(intersect(A,B),C)
댓글 수: 3
Matt Fig
2011년 6월 6일
But you don't have to write a program! The two I pointed you to on the FEX are already written...
Matt Fig
2011년 6월 6일
Here is an example of another way to do it for the many variables case. Note that if you have variables in the workspace which you do not want to be a part of the intersection, just call SAVE with the 3+ argument format, passing only the variables you wish compared:
clear all % Start with a clean slate.
A = round(rand(1,50)*20);
B = round(rand(1,50)*20);
C = round(rand(1,50)*20);
D = round(rand(1,50)*20);
E = round(rand(1,50)*20);
F = round(rand(1,50)*20);
save 'myvars'
X = load('myvars');
F = fieldnames(X);
H = X.(F{1});
for ii = 2:length(F)
H = intersect(H,X.(F{ii}));
end
H % Show the intersection.
추가 답변 (1개)
Morteza Darvish Morshedi
2019년 4월 2일
편집: Morteza Darvish Morshedi
2019년 4월 2일
Hi,
For three input, you can simply do this:
function [Com,ia,ib,ic] = intersect3(A,B,C)
[C1,ia,ib] = intersect(A,B);
[Com,ic1,ic] = intersect(C1,C);
%~ ic is okay
ia = ia(ic1);
ib = ib(ic1);
end
Going from 3 input sets to 5 input sets or more, you would need to follow same procedure, each time on the outputs from the last step. Like (for 4 inputs):
function [Com,ia,ib,ic,id] = intersect4(A,B,C,D)
[C1,ia,ib] = intersect(A,B);
[C2,ic1,ic] = intersect(C1,C);
ia = ia(ic1);
ib = ib(ic1);
% or [C2,ia,ib,ic] = intersect3(A,B,C);
% Now D
[Com,id1,id] = intersect(C2,D);
%~ id is okay
ia = ia(id1);
ib = ib(id1);
ic = ic(id1);
end
댓글 수: 4
Morteza Darvish Morshedi
2020년 3월 7일
Cesar Daniel Castro Having three sets of A,B and C, you always start with finding intersection of two of them, e.g. intersection of A and B as C1. Next, you take intersection between C and C1, as C2. When it comes to indeces of elemtns of C2 in A, B and C, you can directly have those of C from built-in function 'intersect' as ic. To find 'ia' and 'ib', you take a subset of the first intersection C1 that exist in the second intersection C2 as ia=ia(ic1) and ib = ib(ic1). Generalization of this procedure as one function is what Stephen Cobeldick mentioned.
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!