Borrar filtros
Borrar filtros

problem with using randsample

16 visualizaciones (últimos 30 días)
mehdi J
mehdi J el 7 de Nov. de 2018
Comentada: Steven Lord el 6 de Oct. de 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 comentarios
KALYAN ACHARJYA
KALYAN ACHARJYA el 7 de Nov. de 2018
Sorry, the question is not understood. Kindly clarify?
mehdi J
mehdi J el 7 de Nov. de 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

Iniciar sesión para comentar.

Respuesta aceptada

Jeff Miller
Jeff Miller el 7 de Nov. de 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 comentario
Steven Lord
Steven Lord el 6 de Oct. de 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)."

Iniciar sesión para comentar.

Más respuestas (1)

Aaron Schnydrig
Aaron Schnydrig el 6 de Oct. de 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.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by