How to create arrays from repeated matrix raws?
2 次查看(过去 30 天)
显示 更早的评论
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).
0 个评论
采纳的回答
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
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 Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!