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
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 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