A question about sorting a vector

1 view (last 30 days)
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
So is this correct?
Cantor Set
Cantor Set on 8 Sep 2019
A part of a homework problem.
Thank you!

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 7 Sep 2019
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

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by