problem with randsample when array with one element
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jack Ie
am 3 Apr. 2016
Beantwortet: Aaron Schnydrig
am 6 Okt. 2020
when vector has one element, the result of randsample is not correct for my problem. It returns a random number from 1 to that element.
for example:
n=[3];
x = randsample(n,1);
randsample returns x=1 or x=2 or x=3
but I want x=3 only
0 Kommentare
Akzeptierte Antwort
Chad Greene
am 3 Apr. 2016
Perhaps you want
n = 3;
% get a random index no greater than the length of n:
ind = randsample(length(n),1);
% take a random value from n:
x = n(ind)
0 Kommentare
Weitere Antworten (3)
Image Analyst
am 3 Apr. 2016
What do you mean by "when vector has one element"??? WHAT vector? randsample will return 1 number randomly chosen from the vector 1 ..... n, which in your case is [1,2,3] so of course x will be either 1, 2, or 3. What did you expect? If you want x to be 3 or n, simply do this
x = n;
0 Kommentare
Roger Stafford
am 3 Apr. 2016
That's what it is supposed to return. Read the website:
http://www.mathworks.com/help/stats/randsample.html
which states " y = randsample(n,k) returns a k-by-1 vector y of values sampled uniformly at random, without replacement, from the integers 1 to n."
0 Kommentare
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:
x = randsample(repmat(n, 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical 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!