A question about sorting a vector

조회 수: 1 (최근 30일)
Cantor Set
Cantor Set 2019년 9월 7일
댓글: Cantor Set 2019년 9월 8일
Suppose I have a column vector V of length N and I map every element in V to an element y in Y so, we have a column vector Y of length N.
Suppose I want to sort Y in an ascending order and pick r elements from the vector V that corrosponds to the least r values in Y.
I thought of:
V; Y;
N; r;
[Ys idx]=sort(Y);
for i=1:r
Best(i)=V(idx(Ys(i)))
end
Best(i)
So is this correct?
  댓글 수: 2
the cyclist
the cyclist 2019년 9월 7일
편집: the cyclist 2019년 9월 7일
That code gives an error for me. I assume it does for you, too. So, how can it be right?
Is this homework? You are pretty close to a solution, but
idx(Ys(i))
is the wrong way to index, because Ys(i) is not a whole number that can be used in this way.
Cantor Set
Cantor Set 2019년 9월 8일
A part of a homework problem.
Thank you!

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

채택된 답변

Star Strider
Star Strider 2019년 9월 7일
It does not look correct to me, specifically because ‘Ys’ may not necessarily be an integer greater than 0, as required for subscript references in MATLAB, and also within the size limits of ‘V’. (We have no idea what ‘Y’ is, since you have not told us.)
This may give you the result you want, however you have not told us that, either. It nevertheless avoids the explicit loop:
V = randn(10,1); % Create Vector
Y = randn(10,1); % Create Vector
[Ys, idx]=sort(Y);
r = 5; % Choose A Value
Best = V(idx(1:r)) % Result

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by