2012-10-13 30 views
0
A = [8 1 5; 1 4 2; 7 5 2]; 

Max = 5 

B = randi(Max); 

現在我有一部分代碼產生一個隨機數。我正在尋找從數字列表中產生一個隨機數,在這種情況下,第一行中列出的數字(8 1 5)。基於列表生成隨機數是否可行?

而不是使用randi是否有另一個函數會隨機生成第一行中列出的數字之一,也符合Max條件?

回答

1

從你指定的內容,我建議如下:

A = [8 1 5; 1 4 2; 7 5 2]; 

% get a random number from row 1 
index = randperm(length(A(1,:))); 
number = A(1,index(1)) 

% get a randome number from row 1 that does not exceed Max 
max = 5; 
condition = find(A(1,:) <= max); 
index = randperm(length(A(1,condition))); 
number = A(1, condition(index(1))) 

希望這給一些想法,

+1

謝謝!我不知道randperm的功能。 –

0

最簡單的方法是使用arrayfun

B = arrayfun(@randi, A(1,:)) 
+0

謝謝!這可以很容易地修改,只返回該行中的一個數字? –

+0

@JahnnyT:你的意思是'arrayfun(@randi,A(1,[2 2 2]))''? –

+0

不,我期待隨機輸出一個變量而不是三個。在這種情況下'8 1 5'。還有它不超過最大= 5的標準。因此,這個例子的隨機數可以是'1或5'。 –