How to sort a matrix in matlab
Show older comments
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
];
Answers (2)
John Chilleri
on 8 Mar 2017
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 Comments
John Chilleri
on 8 Mar 2017
To generalize the code to any sized matrix:
A(A==0)=Inf;
[C,I] = sort(A);
B = [];
for i = 1:size(A,2)
B = [B I(:,i) C(:,i)];
end
B(B==Inf)=0;
Alex Rob
on 8 Mar 2017
John Chilleri
on 10 Mar 2017
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
on 25 May 2017
Edited: Andrei Bobrov
on 25 May 2017
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)];
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!