using a matrix as an index to another matrix
41 views (last 30 days)
Show older comments
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 ... ?
0 Comments
Accepted Answer
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
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.';
See Also
Categories
Find more on Creating and Concatenating Matrices 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!