필터 지우기
필터 지우기

using a matrix as an index to another matrix

조회 수: 27 (최근 30일)
Andy
Andy 2017년 4월 3일
댓글: Jan 2017년 4월 4일
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 ... ?

채택된 답변

Jan
Jan 2017년 4월 3일
편집: Jan 2017년 4월 4일
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
Andy
Andy 2017년 4월 4일
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 2017년 4월 4일
@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.';

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andy
Andy 2017년 4월 3일
편집: Matt J 2017년 4월 3일
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.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by