How to transpose a matrix

4 次查看(过去 30 天)
Xie
Xie 2017-6-27
编辑: Jan 2017-6-27
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 个评论
Jan
Jan 2017-6-27
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.

请先登录,再进行评论。

回答(2 个)

JESUS DAVID ARIZA ROYETH
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 2017-6-27
编辑:Jan 2017-6-27
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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by