Filter löschen
Filter löschen

problem with using randsample

16 Ansichten (letzte 30 Tage)
mehdi J
mehdi J am 7 Nov. 2018
Kommentiert: Steven Lord am 6 Okt. 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 Kommentare
KALYAN ACHARJYA
KALYAN ACHARJYA am 7 Nov. 2018
Sorry, the question is not understood. Kindly clarify?
mehdi J
mehdi J am 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jeff Miller
Jeff Miller am 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 Kommentar
Steven Lord
Steven Lord am 6 Okt. 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)."

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Aaron Schnydrig
Aaron Schnydrig am 6 Okt. 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.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by