How to transpose a matrix

Matrix A as follows:
A = [1 8
1 5
1 4
2 6
2 7
2 2
2 5
7 6
7 4
7 8
9 9
9 1
9 2
9 6
9 2
];
I want to transpose matrix A based on the unique ID in the first column. Add 0 at the end wherever its needed in order to keep matrix dimension consistent.
out = [1 8 5 4 0 0
2 6 7 2 5 0
7 6 4 8 0 0
9 9 1 2 6 2
];

1 Comment

Jan
Jan on 27 Jun 2017
The procedure is not explained uniquely. Surely this is not a transposing. With some guessing a method can be invented, but it would be safer, if you explain it clearly.

Sign in to comment.

Answers (2)

you can use this:
A = [1 8
1 5
1 4
2 6
2 7
2 2
2 5
7 6
7 4
7 8
9 9
9 1
9 2
9 6
9 2
];
s=unique(A(:,1));
[~,v]=mode(A(:,1));
out=zeros(length(s),v+1);
for k=1:length(s)
value=[s(k) A(A(:,1)==s(k),2)'];
out(k,:)=[value zeros(1,v+1-length(value))];
end
Jan
Jan on 27 Jun 2017
Edited: Jan on 27 Jun 2017
With some guessing:
A = [1 8; ...
1 5; ...
1 4; ...
2 6; ...
2 7; ...
2 2; ...
2 5; ...
7 6; ...
7 4; ...
7 8; ...
9 9; ...
9 1; ...
9 2; ...
9 6; ...
9 2];
[Key, iKey, iA] = unique(A(:, 1));
R = zeros(numel(Key), 1 + mode(iA)); % Pre-allocate
for k = 1:numel(Key)
index = (iA == k);
R(k, 1:sum(index) + 1) = [Key(k), A(index, 2).'];
end
Is the 1st column of A sorted? Then an alternative with FEX: RunLength:
[B, N, Index] = RunLength(A(:, 1));
R = zeros(numel(B), 1 + max(N)); % Pre-allocate
for k = 1:numel(Key)
R(k, 1) = B(k);
R(k, 2:N(k) + 1) = A(Index(k):Index(k)+N(k)-1, 2).';
end

Categories

Asked:

Xie
on 27 Jun 2017

Edited:

Jan
on 27 Jun 2017

Community Treasure Hunt

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

Start Hunting!