MATLAB Answers

How to sort a matrix in matlab

88 views (last 30 days)
Alex Rob
Alex Rob on 8 Mar 2017
Edited: Andrei Bobrov on 25 May 2017
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
];

  0 Comments

Sign in to comment.

Answers (2)

John Chilleri
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
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
Alex Rob on 8 Mar 2017
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 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!

Sign in to comment.


Andrei Bobrov
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)];

  0 Comments

Sign in to comment.