Does something similar to 'intersect' command exists for more than 2 vectors?
Mostrar comentarios más antiguos
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.
Respuesta aceptada
Más respuestas (1)
Morteza Darvish Morshedi
el 2 de Abr. de 2019
Editada: Morteza Darvish Morshedi
el 2 de Abr. de 2019
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 comentarios
This can be generalized using a loop:
function [A,ia,varargout] = intersectm(A,varargin)
varargout = cell(size(varargin));
ia = 1:numel(A);
for ii = 1:numel(varargin)
[A,ixa,varargout{ii}] = intersect(A,varargin{ii});
ia = ia(ixa);
for jj = 1:ii-1
varargout{jj} = varargout{jj}(ixa);
end
end
end
Morteza Darvish Morshedi
el 2 de Abr. de 2019
Correct. Thanks.
Cesar Daniel Castro
el 4 de Mzo. de 2020
Could you please give more details about your code?
Morteza Darvish Morshedi
el 7 de Mzo. de 2020
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.
Categorías
Más información sobre MATLAB en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!