Randomly return of a vector element. How to?

1 回表示 (過去 30 日間)
Tasos Ampelas
Tasos Ampelas 2018 年 7 月 5 日
回答済み: dpb 2018 年 7 月 5 日
Hi everyone,
I have a vector A, of let's say, 30 elements.
I need Matlab (R2017b) to return the same element constantly and at random times return one of the rest elements, randomly chosen.
How can I do such a thing?
  4 件のコメント
Tasos Ampelas
Tasos Ampelas 2018 年 7 月 5 日
Thank you Dennis.
The ''if prob == 1'' gives the chance of the random pick right?
So if I write ''if prob == 2,5'' this will be 1 random pick in 4?
Dennis
Dennis 2018 年 7 月 5 日
編集済み: Dennis 2018 年 7 月 5 日
randi only provides natural numbers (1,2,3,4). If you want a chance of 1 in 4 change the line above to
prob = randi(4);
short explanation:
prob = randi(4); %creates a random integer between 1 and 4 (1,2,3 or 4)
if prob ==1 % checks if the random integer is 1

サインインしてコメントする。

回答 (1 件)

dpb
dpb 2018 年 7 月 5 日
ixFix = N; % set the particular element however is to be done...
iRet=[ixFix randperm(numel(A),1)]; % index vector of positions to return
B=A(iRet); % and get them...
Can, of course, eliminate temporaries shown for clarity if not needed for other purposes in the application.
B=A([N randperm(numel(A),1)]);

カテゴリ

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