all possible combination between matrices

조회 수: 1(최근 30일)
jean claude
jean claude 2020년 10월 28일
댓글: Bruno Luong 2020년 10월 29일
I have 3 matrices with 2 columns but different number of lines, for example;
B = [[0,2],[1,1],[3,4],[0,5]
C = [[0,1],[5,4]]
i want to do all the combinations between,each pairs A/B and B/C for a difference of +1 or -1 between the sum of each pair, and they must have a number in common. For example if we take [2,1] from A, the sum is 3=2+1 now i have to find the next pair in B (if exist), see that [0,2] the sum is 2=0+2 and there is a number in common with [2,1] from A so i keep this pair and i dont keep [1,1] cause there is no common number, now if i go to C i will take [0,1] cause the sum is 1=0+1 and there is number in common with [1,1], passing from A to B, B to C respecting -1 sum difference and having always a number in common between the previous pair and the chosen one.
So the result in this case must be
[2,1], [0,2], [0,1]
  댓글 수: 1
Bruno Luong
Bruno Luong 2020년 10월 29일
"dont keep [1,1] cause there is no common number"
Why you said that? It has 1 in common with [2,1] from A.

댓글을 달려면 로그인하십시오.

채택된 답변

Akira Agata
Akira Agata 2020년 10월 29일
Seems to be an interesting 'puzzle'.
Though this is not so smart, how about the following?
%% Data
A = {[2,1],[0,6],[4,2]};
B = {[0,2],[1,1],[3,4],[0,5]};
C = {[0,1],[5,4]};
%% Compare A and B
sumA = cellfun(@sum,A);
sumB = cellfun(@sum,B);
idx1 = abs(sumA - sumB') == 1;
c1 = cellfun(@intersect,repmat(A,4,1),repmat(B',1,3),'UniformOutput',false);
idx2 = cellfun(@(x) ~isempty(x),c1);
idxAll = idx1 & idx2;
[row,col] = find(idxAll);
T1 = table(cell2mat(A(col)'),cell2mat(B(row)'),'VariableNames',{'A','B'});
%% Compare B and C
sumC = cellfun(@sum,C);
idx1 = abs(sumB - sumC') == 1;
c2 = cellfun(@intersect,repmat(B,2,1),repmat(C',1,4),'UniformOutput',false);
idx2 = cellfun(@(x) ~isempty(x),c2);
idxAll = idx1 & idx2;
[row,col] = find(idxAll);
T2 = table(cell2mat(B(col)'),cell2mat(C(row)'),'VariableNames',{'B','C'});
%% Apply innerjoin to obtain the final result
Tall = innerjoin(T1,T2,'Keys','B');
There seems to be two comtinations:
>> Tall
Tall =
2×3 table
______ ______ ______
2 1 0 2 0 1
2 1 1 1 0 1

추가 답변(0개)


Community Treasure Hunt

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

Start Hunting!

Translated by