How to output a random element from a vector in matlab?
古いコメントを表示
I want to create a function called choose, where for example i can put in the command window choose(1:10) and the output would be a random number from 1 to 10. How do I do that?
回答 (2 件)
Walter Roberson
2015 年 9 月 20 日
choose = @(samples) samples(randi(numel(samples)));
2 件のコメント
per isakson
2015 年 9 月 20 日
That's clever!
Torsten
2022 年 4 月 3 日
Say you have a vector x of n numbers :
x = (x(1),x(2),...,x(n))
Now choosing a random element from this vector means to choose a number between 1 and n randomly and then return the element of x corresponding to that number. E.g. if 5 is chosen, x(5) is returned.
MATLAB's function "randi" can be used for this purpose. The command
randi(n)
returns a random integer between 1 and n.
So if you have a vector x, you can choose a random element from this vector by doing
n = numel(x); % determines the number of elements of vector x
i = randi(n); % returns a random integer between 1 and n
xrand = x(i); % xrand is the randomly chosen element from vector x
per isakson
2015 年 9 月 20 日
One way
>> cssm(1:10)
ans =
2
>> cssm([3,6,9,12,1,2])
ans =
3
>> cssm(1:10)
ans =
6
>> cssm([3,6,9,12,1,2])
ans =
2
where
function val = cssm( vec )
ix = randi([1,length(vec)]);
val = vec(ix);
end
3 件のコメント
Hussam Alzahrani
2015 年 9 月 20 日
per isakson
2015 年 9 月 20 日
編集済み: per isakson
2015 年 9 月 20 日
- see:   randi, Uniformly distributed pseudorandom integers
- see:   Examine Values While Debugging
- set a break point at the first line of the function
- call the function
- etc.
Lawrence Prophete
2020 年 2 月 20 日
ix randomixes the index from 1 to the length of the vector, then val is the value of the randomized index
カテゴリ
ヘルプ センター および File Exchange で Environment and Settings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!