How to transpose a matrix

3 ビュー (過去 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
JESUS DAVID ARIZA ROYETH 2017 年 6 月 27 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by