How to create arrays from repeated matrix raws?

2 ビュー (過去 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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by