Are there any functions to randomly pick the minimum element from a vector if the vector has multiple minimum elements?

Function min() picks the first minimum element from a vector if the vector has multiple minimum elements.
I want to randomly pick the minimum element from all the minimum elements and get its value and index.
Could you tell me if there is a function to do that?

 Accepted Answer

No, there is no function provided for that. You can write such a function, though. The difficulty of doing it will depend upon whether you are working with a vector or something that is at least 2D (in which case it has to process per row or per column)

5 Comments

For the scalar case:
minval = min(TheVector);
idx = find(TheVector == minval);
idx = idx(randi(length(idx)));
The code is great and illuminating!
Actually, I want to randomly pick the minimum element consecutively three times as follows.
Step 1, I randomly pick the minimum element among all the minimum elements and get its value and index.
Step 2, I exclude the element picked in Step 1 and randomly pick the minimum element among all the minimum elements and get its value and index.
Step 3, I exclude the elements picked in Step 1 and Step 2 and randomly pick the minimum element among all the minimum elements and get its value and index.
Could you further help me?
That sounds like homework.
I will give a hint: if you set a value to nan then it will no longer be a minimum (unless everything is nan.)
Thanks a lot!
Actually, I though of setting the value as Inf. But I am afraid the program will have bugs during the later programming. Seriously...
It is not homework. Seriously...
Anyway, thanks a lot!
NR = 3;
[sortedvals, sortidx] = sort(YourVector);
LastSameIdx = 1;
MinVals = zeros(1,NR);
RandomIdx = zeros(1,NR);
for K = 1 : NR
LastSameIdx = 1;
while LastSameIdx < length(YourVector) && sortedvals(1) == sortedvals(LastSameIdx+1)
LastSameIdx = LastSameIdx + 1;
end
thisidx = randi(LastSameIdx);
MinVals(K) = sortedvals(thisidx);
RandomIdx(K) = sortidx(thisidx);
sortedvals(thisidx) = [];
sortidx(thisidx) = [];
end
Outputs are MinVals and RandomIdx.

Sign in to comment.

More Answers (0)

Products

Release

R2019b

Tags

Community Treasure Hunt

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

Start Hunting!