MATLAB: Using a matrix as an index to another matrix

loops are fasterMATLABusing a matrix as an index to another matrix

Simple case:
>> x = [ 10 8 ; 4 3 ]
x =
10 8
4 3
>> [y,i] = sort(x,2 )
y =
8 10
3 4
i =
2 1
2 1
>> x(i)
ans =
4 10
4 10
We see x(i) is not equiv. to y. Can I use x & i to derive y … ?

Best Answer

3 versions with a speed comparison:
function speedtest
x = rand(2000, 1000);
tic;
for k = 1:5
% Method 1: SUB2IND:
[y, idx2] = sort(x, 2);
sx = size(x);
index = sub2ind(sx, repmat((1:sx(1)).', 1, sx(2)), idx2);
y2 = x(index);
end
toc
tic;
for k = 1:5
% Method 2: Simplified loop, row-wise
[y, idx2] = sort(x, 2);
y3 = zeros(size(x));
for r = 1:size(x,1)
y3(r, :) = x(r, idx2(r, :));
end
end
toc
tic;
for k = 1:5
% Method 3: Simplified loop, column-wise
xt = x.';
[yt, idx1] = sort(xt, 1);
y4 = zeros(size(xt));
for r = 1:size(x,1)
y4(:, r) = xt(idx1(:, r), r);
end
y4 = y4.';
end
toc
isequal(y, y2, y3, y4)
Matlab 2009a/64, Win7, 2 cores of an i5 in a VM:
Elapsed time is 2.174286 seconds. % SUB2IND
Elapsed time is 2.512037 seconds. % Loop, rowwise
Elapsed time is 0.706579 seconds. % Loop, columnwise
The cloumn-wise loop method is faster for [200, 10000] and [10000, 200] inputs also.