Effacer les filtres
Effacer les filtres

problem with using randsample

16 vues (au cours des 30 derniers jours)
mehdi J
mehdi J le 7 Nov 2018
Commenté : Steven Lord le 6 Oct 2020
Hi, I have a set that its members change in a loop and I want to select just one member of it randomly and evaluate the result. the written code is as below:
CandidateNode = randsample(UnvisitedNode,1);
it works good but sometimes its result is not acceptable. for example when UnvisitedNode=[3] running this code have different result. sometimes CandidateNode=[1], sometimes CandidateNode=[2] and sometimes CandidateNode=[3] how could I fix it? tanx in advanced
  2 commentaires
KALYAN ACHARJYA
KALYAN ACHARJYA le 7 Nov 2018
Sorry, the question is not understood. Kindly clarify?
mehdi J
mehdi J le 7 Nov 2018
as you know: "y = randsample(population,k) returns a vector of k values sampled uniformly at random, without replacement, from the values in the vector population." but when the population is a vector with one member (for example population=[5]), for k=1 you will receive meaningless result.
>> randsample([5],1)
ans =
1
>> randsample([5],1)
ans =
4

Connectez-vous pour commenter.

Réponse acceptée

Jeff Miller
Jeff Miller le 7 Nov 2018
When the first parameter of randsample is a single number k, the assumption is that you want a random sample from the integers 1:k. It looks like you will have to check numel(UnvisitedNode) and return its value when numel=1.
  1 commentaire
Steven Lord
Steven Lord le 6 Oct 2020
Alternately you could use randi instead of randsample for this particular use case.
% Build some sample data
numberOfNodes = randi(10); % Random number of nodes
UnvisitedNode = (1:numberOfNodes).^2
% Choose one of the UnvisitedNodes
selectedNode = UnvisitedNode(randi(numel(UnvisitedNode)))
This is a variant of the suggestion given in the description of the population input argument on the documentation page for the randsample function:
"If population is a numeric vector containing only nonnegative integer values, and population can have the length 1, then use y = population(randsample(length(population),k)) instead of y = randsample(population,k)."

Connectez-vous pour commenter.

Plus de réponses (1)

Aaron Schnydrig
Aaron Schnydrig le 6 Oct 2020
The question is quite old, but for the ones finding it over Google (like I did):
The simplest answer would be the following:
CandidateNode = randsample(repmat(UnvisitedNode, 2, 1),1)
The repmat() function uses every value of your vector twice. Therefore, it will not change the probability of a certain element. However, it will make sure that your vector always has more than one element and is therefore used as a population.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by