using a matrix as an index to another matrix

39 views (last 30 days)
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 ... ?

Accepted Answer

Jan
Jan on 3 Apr 2017
Edited: Jan on 4 Apr 2017
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.
  2 Comments
Andy
Andy on 4 Apr 2017
thanks, and if I want to return a matrix similar to y, but instead of having all (ordered) values present, just to keep highest N on each row, and fill with zero / nan all the other values. The highest N values on each row, should also keep their original column position (they had in x). Is this something easy to be built on the above code?
Jan
Jan on 4 Apr 2017
@Andrei: This is a different question. Prefer to open a new thread for a new problem in the future.
N = 4; % Keep the 4 largest values at their positions:
xt = x.';
[ys, idx1] = sort(xt, 1, 'descend');
y = NaN(size(xt));
for r = 1:size(xt, 2)
y(idx1(1:4, r), r) = ys(1:4, r);
end
y = y.';

Sign in to comment.

More Answers (1)

Andy
Andy on 3 Apr 2017
Edited: Matt J on 3 Apr 2017
I could do this:
clc;
a = [1 4 3 2; 6 8 7 9]
[b,i] = sort(a,2,'descend')
b = zeros(size(a,1),size(a,2));
for r = 1:size(a,1)
for c = 1:size(a,2)
b(r,c) = a(r, i(r,c));
end
end
b
a =
1 4 3 2
6 8 7 9
b =
4 3 2 1
9 8 7 6
i =
2 3 4 1
4 2 3 1
b =
4 3 2 1
9 8 7 6
nonetheless, it's so not elegant ... and not too high performance for large sizes.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!