Combine and sorting array values

조회 수: 11 (최근 30일)
L. Edwin M.
L. Edwin M. 2022년 4월 13일
댓글: L. Edwin M. 2022년 4월 16일
Hello!
I got a result matrix A
A = [3 9 4]
And another matrix B
[ 3 8
4 8
15 5
B= 16 1
16 2
16 7
17 6
17 2 ]
First i want to combine A with all values of the second column of B that have a unique value in the first column -> Matrix AB
AB = [3 9 4 8 5]
As a final result i want the combinations of AB with all values of the second column of B that have not a unique value in the first column ->Result
Result= [3 9 4 8 5 1 6 3 9 4 8 5 1 2
3 9 4 8 5 2 6 3 9 4 8 5 2 2
3 9 4 8 5 7 6 3 9 4 8 5 7 2]
How can i do that?
Many thanks in advance!

채택된 답변

DGM
DGM 2022년 4월 13일
편집: DGM 2022년 4월 13일
Maybe something like:
A = [3 9 4];
B = [3 8
4 8
15 5
16 1
16 2
16 7
17 6
17 2];
U = unique(B(:,1));
c = histcounts(B(:,1),U);
col1unique = ismember(B(:,1),U(c==1));
AB = [A unique(B(col1unique,2),'stable').']
AB = 1×5
3 9 4 8 5
combpool = unique(B(~col1unique,2));
combs = nchoosek(combpool,2);
result = [repmat(AB,[size(combs,1) 1]) combs]
result = 6×7
3 9 4 8 5 1 2 3 9 4 8 5 1 6 3 9 4 8 5 1 7 3 9 4 8 5 2 6 3 9 4 8 5 2 7 3 9 4 8 5 6 7
If you want the result formatted as shown, then:
result = reshape(result.',size(result,2)*2,[]).'
result = 3×14
3 9 4 8 5 1 2 3 9 4 8 5 1 6 3 9 4 8 5 1 7 3 9 4 8 5 2 6 3 9 4 8 5 2 7 3 9 4 8 5 6 7
  댓글 수: 6
DGM
DGM 2022년 4월 16일
Oh I misunderstood what kind of combinations you were after. I was just doing combinations of all remaining (unique) elements of col2.
This does combinations of the groups within col2 associated with the nonunique blocks in col1
A = [3 9 4];
B = [3 8
4 8
15 5
16 1
16 2
16 7
17 6
17 2];
[c ed] = histcounts(B(:,1),'binmethod','integers');
col1unique = ismember(B(:,1),ed(c==1)+0.5);
AB = [A unique(B(col1unique,2),'stable').']
AB = 1×5
3 9 4 8 5
% split col2 of B into groups associated with nonunique elements of col1
Bnonu = B(~col1unique,:);
g = findgroups(Bnonu(:,1));
ngroups = max(g);
elements = cell(1,ngroups);
for k = 1:ngroups
elements{k} = Bnonu(g==k,2);
end
% find combinations of elements between groups
combinations = cell(1,ngroups); %set up the varargout result
[combinations{:}] = ndgrid(elements{:});
combinations = cellfun(@(x) x(:), combinations,'uniform',false);
result = [combinations{:}];
result = [repmat(AB,[size(result,1) 1]) result]
result = 6×7
3 9 4 8 5 1 6 3 9 4 8 5 2 6 3 9 4 8 5 7 6 3 9 4 8 5 1 2 3 9 4 8 5 2 2 3 9 4 8 5 7 2
based on this:
L. Edwin M.
L. Edwin M. 2022년 4월 16일
Many thanks!!!!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by