问题
I have two cell arrays which may not be of the same size. Elements of cell arrays is randperm
of an integer number. randperm
data Type is double array. How can I find common elements of two cell arrays?
For example:
Q1 = {[1 2 3 4], [3 2 4 1], [4 2 1 3]}
Q2 = {[2 4 3 1], [1 2 3 4], [1 2 4 3]}
As I said elements of cell arrays are randperm
. I want the output of above example be "Element-1 of Q1
i.e. [1 2 3 4]
since it is also present in Q2
.
Note: Cell Arrays may have different number of columns...
回答1:
Vertically concatenate the matrices inside the cell arrays and use intersect
with the 'rows' flag. i.e.
Q1={[1 2 3 4], [3 2 4 1], [4 2 1 3]};
Q2={[2 4 3 1], [1 2 3 4], [1 2 4 3]};
Qout = intersect(vertcat(Q1{:}), vertcat(Q2{:}), 'rows');
%>> Qout
%Qout =
% 1 2 3 4
回答2:
You can do it by using two loops and check all off them.
q1=[1 2 3 4; 3 2 4 1; 4 2 1 3];
q2=[2 4 3 1; 1 2 3 4; 1 2 4 3];
%find the size of matrix
[m1,n1] = size(q1);
[m2] = size(q2,1);
for (ii=1:m1)
for (jj=1:m2)
%if segments are equal, it will return 1
%if sum of same segment = 4 it means they are same
if ( sum( q1(ii,:) == q2(jj,:) ) == n1)
ii %result of q1
jj %result of q2
break;
end
end
end
来源:https://stackoverflow.com/questions/44913957/how-to-find-the-common-elements-of-2-cell-arrays-that-contain-randperm-elements