2014-10-19 81 views
1

所以我想要做的只是從matlab中的邏輯矩陣中選擇隨機'1'元素。 假設我有一個這樣的矩陣:從邏輯矩陣中選擇隨機'1'元素

A= 0 1 1 1 0 
    0 1 0 1 1 
    1 0 0 0 0 
    0 0 1 0 0 
    0 0 0 0 0 

和我的數Ñ這是一個數字,代表有多少「1」的元件將在程序

例如被選擇,如果n=3則輸出可以是如下所示:

A'= 0 1 0 0 0 
    0 0 0 0 1 
    0 0 0 0 0 
    0 0 1 0 0 
    0 0 0 0 0 

*注意可能對於n的最大值爲是「1」的元素在基體中的數ING處理

回答

5

你應該找到1秒的指標,選擇n獨特的隨機整數,並處理這些索引:

n = 3; 
A= [0 1 1 1 0; 
    0 1 0 1 1; 
    1 0 0 0 0; 
    0 0 1 0 0; 
    0 0 0 0 0]; 

% // idx of the ones in the matrix, also has information on size 
idx = find(A == 1); 

% // n unique rand numbers from 1 till nr_of_ones 
randidx = randperm(numel(idx), n); 

% // new matrix 
B = zeros(size(A)); 

% // select the random indexes 
B(idx(randidx)) = 1