필터 지우기
필터 지우기

How to create arrays from repeated matrix raws?

조회 수: 1 (최근 30일)
Philippe Corner
Philippe Corner 2020년 10월 16일
댓글: Philippe Corner 2020년 12월 2일
If we have a matrix A like:
A=[
1 2 3 4 5
1 2 8 9 10
1 2 13 14 15
11 12 16 27 18
11 12 19 29 21
11 12 22 23 24];
As you can see, the A(:,1:2), has repeated values each 3 raws. I would like to create "arrays" for each repeated raw values on A(:,1:2), and obtain a matrix B that creates new columns for the raws of repeated values like:
B=[
1 2 3 4 5 8 9 10 13 14 15
11 12 16 27 18 19 29 21 22 23 24];
Next image sumarizes the problem with colors for the final location of the raws creating 2 arrays for the repeated A(:,1:2).

채택된 답변

Stephen23
Stephen23 2020년 10월 16일
편집: Stephen23 2020년 10월 16일
>> A = [1,2,3,4,5;1,2,8,9,10;1,2,13,14,15;11,12,16,27,18;11,12,19,29,21;11,12,22,23,24]
A =
1 2 3 4 5
1 2 8 9 10
1 2 13 14 15
11 12 16 27 18
11 12 19 29 21
11 12 22 23 24
>> [U,X,Y] = unique(A(:,1:2),'rows');
>> F = @(r)reshape(A(Y==r,3:end).',1,[]);
>> C = arrayfun(F,1:max(Y),'uni',0);
>> M = [U,vertcat(C{:})]% optional (only works if number of columns is the same)
M =
1 2 3 4 5 8 9 10 13 14 15
11 12 16 27 18 19 29 21 22 23 24

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 10월 16일
편집: Ameer Hamza 2020년 10월 16일
An alternative approach
A=[
1 2 3 4 5
1 2 8 9 10
1 2 13 14 15
11 12 16 27 18
11 12 19 29 21
11 12 22 23 24];
rows = find([1; any(diff(A(:,1:2)), 2)]);
B = [A(rows, 1:2) reshape(A(:,3:end).', (size(A,2)-2)*diff(rows(1:2)), []).'];
Result
>> B
B =
1 2 3 4 5 8 9 10 13 14 15
11 12 16 27 18 19 29 21 22 23 24

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by