# How to sort a matrix with the second row depending on the sorting of the first row?

7 views (last 30 days)
Thomas Nell on 12 Dec 2018
Commented: Thomas Nell on 13 Dec 2018
Hey guys,
I have 2 vectors, time and signal, with corresponding vectors [ 1 3 2 4 7] and [12 14 11 13 16]. I have this quicksort code:
function dataOut = Quicksort(data)
lenD = size(data,2);
ind = cast(floor(lenD/2),'uint8');
j = 1;
k = 1;
L = [];
R = [];
if(lenD<2)
dataOut = data;
else
pivot = data(ind);
for i=1:lenD
if(i~=ind)
if(data(i)<pivot)
L(j) = data(i);
j = j+1;
else
R(k) = data(i);
k = k+1;
end
end
end
L = Quicksort(L);
R = Quicksort(R);
dataOut = [L pivot R];
end
---------------------------------
It works well for only 1 vector, but what I ideally want is the 2nd vector to move in correspondance with the first, i.e the sorted vectors become: [1 2 3 4 7] and [12 11 14 13 16]. I cannot use the sort command. How do I go about this???
Kind regards,
Tom

Stephen23 on 13 Dec 2018
Edited: Stephen23 on 13 Dec 2018
One easy way to obtain indices from any sorting algorithm is to "hang" some indices onto the data before sorting, and apply exactly the same permutations to those indices as are applied to the data themselves. I wrapped your function in another one to make this a bit easier to implement:
function [out,idx] = quicksort(vec)
assert(isrow(vec),'Input must be a row vector')
Z = qsRecFun([vec;1:numel(vec)]);
out = Z(1,:);
idx = Z(2,:);
end
function Sm = qsRecFun(M)
N = size(M,2);
if N<2
Sm = M;
else
jj = 1;
kk = 1;
Lm = [];
Rm = [];
X = fix(N/2);
P = M(:,X);
for ii = [1:X-1,X+1:N]
if M(1,ii)<P(1)
Lm(:,jj) = M(:,ii);
jj = jj+1;
else
Rm(:,kk) = M(:,ii);
kk = kk+1;
end
end
Lm = qsRecFun(Lm);
Rm = qsRecFun(Rm);
Sm = [Lm,P,Rm];
end
end
And checking the output against that of MATLAB's sort:
>> V = randi(9,1,7)
V =
9 5 3 8 1 6 2
>> [Y,X] = quicksort(V)
Y =
1 2 3 5 6 8 9
X =
5 7 3 2 6 4 1
>> [Y,X] = sort(V)
Y =
1 2 3 5 6 8 9
X =
5 7 3 2 6 4 1
Note that you could also improve the code by using logical indexing, although this would look less like the naive algorithm itself.
Thomas Nell on 13 Dec 2018
Stephen, you're a genius, thanks so much man.