フィルターのクリア

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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by