Filter löschen
Filter löschen

How to create arrays from repeated matrix raws?

1 Ansicht (letzte 30 Tage)
Philippe Corner
Philippe Corner am 16 Okt. 2020
Kommentiert: Philippe Corner am 2 Dez. 2020
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).

Akzeptierte Antwort

Stephen23
Stephen23 am 16 Okt. 2020
Bearbeitet: Stephen23 am 16 Okt. 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

Weitere Antworten (1)

Ameer Hamza
Ameer Hamza am 16 Okt. 2020
Bearbeitet: Ameer Hamza am 16 Okt. 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

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by