all possible combination between matrices

1 visualización (últimos 30 días)
jean claude
jean claude el 28 de Oct. de 2020
Comentada: Bruno Luong el 29 de Oct. de 2020
I have 3 matrices with 2 columns but different number of lines, for example;
A=[[2,1],[0,6],[4,2]]
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 comentario
Bruno Luong
Bruno Luong el 29 de Oct. de 2020
"dont keep [1,1] cause there is no common number"
Why you said that? It has 1 in common with [2,1] from A.

Iniciar sesión para comentar.

Respuesta aceptada

Akira Agata
Akira Agata el 29 de Oct. de 2020
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');
Result:
There seems to be two comtinations:
>> Tall
Tall =
2×3 table
A B C
______ ______ ______
2 1 0 2 0 1
2 1 1 1 0 1

Más respuestas (0)

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by