How to rearrange an array ? (only unique numbers in a column)

How to rearrange matrix: A = [1 1;1 4;2 3;2 7;3 5;4 2;5 6] To make it looks like: B= [1 1 4;2 3 7; 3 5 0; 4 2 0; 5 6 0]
The idea is to have only unique values in first column and if (in this example "1" and "2") value used twice to keep both numbers? Thanks

 Accepted Answer

A = [1 1;1 4;2 3;2 7;3 5;4 2;5 6] ,
c=accumarray(A(:,1),A(:,2),[],@(x) {x})
n=max(cellfun(@numel,c));
B=[unique(A(:,1),'stable') cell2mat(cellfun(@(x) [x' zeros(1,n-numel(x)) ],c,'un',0))]

3 Comments

Thank you, Azzi! It works for this example. But my original matrix A is 500x2 size and few numbers in first column are repeated up to 33 times. I cannot figure out what needs to be change in your code. Can you help me, please?

Sign in to comment.

More Answers (0)

Categories

Products

Community Treasure Hunt

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

Start Hunting!