How to sort a matrix in matlab

조회 수: 17 (최근 30일)
Alex Rob
Alex Rob 2017년 3월 8일
편집: Andrei Bobrov 2017년 5월 25일
Assume matrix A as follows:
A = [...
1 50 0 10
2 0 0 0
3 0 30 0
4 0 15 0
5 45 0 65
6 55 0 0
7 0 10 0
8 0 0 90
9 0 0 5
10 10 0 0
];
I want to sort the matrix A column 2:4 and produce matrix B. In matrix B pair of successive columns are represent to sorted array of first and corresponded column in matrix A.
B = [...
10 10 7 10 1 10
5 45 4 15 5 65
1 50 3 30 8 90
6 55 1 0 2 0
2 0 2 0 3 0
3 0 5 0 4 0
4 0 6 0 6 0
7 0 8 0 7 0
8 0 9 0 9 0
9 0 10 0 10 0
];

답변 (2개)

John Chilleri
John Chilleri 2017년 3월 8일
Hello,
The sort function can do this for you,
% Given your A - first column:
A = [50 0 10
0 0 0
0 30 0
0 15 0
45 0 65
55 0 0
0 10 0
0 0 90
0 0 5
10 0 0];
% Set 0s to infinity to place them after in sort (will switch back to 0s):
A(A==0)=Inf;
[C,I] = sort(A);
B = [I(:,1) C(:,1) I(:,2) C(:,2) I(:,3) C(:,3)];
B(B==Inf)=0;
which results with,
>> B
B =
10 10 7 10 9 5
5 45 4 15 1 10
1 50 3 30 5 65
6 55 1 0 8 90
2 0 2 0 2 0
3 0 5 0 3 0
4 0 6 0 4 0
7 0 8 0 6 0
8 0 9 0 7 0
9 0 10 0 10 0
Hope this helps!
  댓글 수: 3
Alex Rob
Alex Rob 2017년 3월 8일
Great job John!
Can I have now matrix B with the following format:
B = [1 10 10
1 5 45
1 1 50
1 6 55
2 7 10
2 4 15
2 3 30
3 9 5
3 1 10
3 5 65
3 8 90
];
% in the new format all rows include 0 are removed and first column got similar index 1:3 (because we had 3 columns in matrix A)
John Chilleri
John Chilleri 2017년 3월 10일
Yes,
If you use:
count = 1;
for i = 2:2:size(B,2)
for j = 1:size(B,1)
if (B(j,i) ~= 0)
C(count,1:3) = [i/2 B(j,i-1) B(j,i)];
count = count + 1;
end
end
end
It will produce the desired C,
>> C
C =
1 10 10
1 5 45
1 1 50
1 6 55
2 7 10
2 4 15
2 3 30
3 9 5
3 1 10
3 5 65
3 8 90
Hope this helps!

댓글을 달려면 로그인하십시오.


Andrei Bobrov
Andrei Bobrov 2017년 5월 25일
편집: Andrei Bobrov 2017년 5월 25일
A = [1 50 0 10
2 0 0 0
3 0 30 0
4 0 15 0
5 45 0 65
6 55 0 0
7 0 10 0
8 0 0 90
9 0 0 5
10 10 0 0
];
[m,n] = size(A);
B = zeros([m,2*(n-1)]);
B(:,2:2:end) = A(:,2:end);
B(B == 0) = nan;
[B(:,2:2:end),ii] = sort(B(:,2:2:end));
B(:,1:2:end) = ii;
B(isnan(B)) = 0;
Bout = permute(reshape(B,m,2,[]),[1,3,2]);
t = Bout(:,:,2) ~= 0;
[~,jj] = find(t);
out = [jj,reshape(Bout(repmat(t,1,1,2)),[],2)];

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by