필터 지우기
필터 지우기

problem with using randsample

조회 수: 16 (최근 30일)
mehdi J
mehdi J 2018년 11월 7일
댓글: Steven Lord 2020년 10월 6일
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
KALYAN ACHARJYA
KALYAN ACHARJYA 2018년 11월 7일
Sorry, the question is not understood. Kindly clarify?
mehdi J
mehdi J 2018년 11월 7일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Jeff Miller
Jeff Miller 2018년 11월 7일
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
Steven Lord
Steven Lord 2020년 10월 6일
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)."

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Aaron Schnydrig
Aaron Schnydrig 2020년 10월 6일
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.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by