how do i select a number from a set randomly

4 ビュー (過去 30 日間)
Romy Schipper
Romy Schipper 2017 年 5 月 18 日
回答済み: James Tursa 2017 年 5 月 18 日
I want to select 1 or -1, my code now looks like this:
if true
% code
for i = 1:101
for j = 1:5
%action may be -1 or 1
ac = [-1,1];
posA = randi(length(ac));
Asimulac(i,j) = ac(posA);
posB = randi(length(ac));
Bsimulac(i,j) = ac(posB);
end
end
end
It works but posA and posB keeps being the same for every loop in j=1:5, which is not what I want. In otherwords Asimulac(i,j) = Bsimulac(i,j). How do I really randomly draw from the set [-1,1]?

回答 (2 件)

Stephen23
Stephen23 2017 年 5 月 18 日
編集済み: Stephen23 2017 年 5 月 18 日
V = [-1,+1]; % or any set of values
V(randperm(numel(V),1)) % pick one out of the set

James Tursa
James Tursa 2017 年 5 月 18 日
If you are just interested in the values -1 and 1, you could do something like this:
Asimulac = round(rand(101,5))*2-1;
Bsimulac = round(rand(101,5))*2-1;

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by