How to create arrays from repeated matrix raws?

2 views (last 30 days)
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).

Accepted Answer

Stephen23
Stephen23 on 16 Oct 2020
Edited: Stephen23 on 16 Oct 2020
>> 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

More Answers (1)

Ameer Hamza
Ameer Hamza on 16 Oct 2020
Edited: Ameer Hamza on 16 Oct 2020
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

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!