MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

Naime
0

choose 2 random unique element inside cell

Naime
さんによって質問されました 2019 年 2 月 23 日
最新アクティビティ Jos (10584)
さんによって コメントされました 2019 年 2 月 25 日
how to choose 2 random unique element inside a cell?
index={[1,2,5,9,10,13,17,18,21],[4,5,7,12,13,15,18,20,21],[3,4,6,11,12,14,18,19,20],[8,16,20,22]};
example of result
p={[1,9],[7,21],[3,4],[16,8]}

  0 件のコメント

サインイン to comment.

2 件の回答

回答者: per isakson
2019 年 2 月 23 日
編集済み: per isakson
2019 年 2 月 23 日
 採用された回答

and try
>> cellfun( @(row) datasample( row, 2, 'replace',false ), index, 'uni',false )
ans =
1×4 cell array
{1×2 double} {1×2 double} {1×2 double} {1×2 double}
"[...] random unique element inside a cell" does that mean without replacement?
If it means literal "unique elements" then run this is a first step to remove duplicates.
>> index = cellfun( @unique, index, 'uni',false )
ix =
1×4 cell array
{1×9 double} {1×9 double} {1×9 double} {1×4 double}
Or should the propability to pick a specific value be proportional to the number of duplicates of that value?

  8 件のコメント

Naime
2019 年 2 月 24 日
I want to do something like this
if iteration==1
changed_mes_index=cellfun( @(m) datasample( m, changed_num, 'replace',false ), index, 'uni',false );
end
this code
index = repmat( index, 5,1 );
out = cellfun( @(row) datasample( row, 2, 'replace',false ), index, 'uni',false )
does not give what I want
Naime
2019 年 2 月 24 日
amount is calculated by adding normrnd. so it changes in each iteration.
per isakson
2019 年 2 月 24 日
"amount is calculated by adding normrnd" That means that you need to be careful regarding Accuracy of Floating-Point Data
So far, I have assumed whole numbers

サインイン to comment.


回答者: Jos (10584)
2019 年 2 月 23 日

If I understand you correctly, the final output should have 8 unique numbers, in four groups of two, where the numbers in each group is drawn from a cell in the cell array index. This is not a trivial problem to answer! There might situations where this is simply impossible given a cell array index (for instance index= {[1 2 3], [1 2 4], [2 3 4],... }
You might want to try a brute-force method
index={[1,2,5,9,10,13,17,18,21],[4,5,7,12,13,15,18,20,21],[3,4,6,11,12,14,18,19,20],[8,16,20,22]};
fn = @(v) sort(v(randperm(numel(v),2))) ; % function to draw 2 randomelements from v
k = 1 ;
while k < 1e5 % try a lot of times
C = cellfun(fn, index,'un',0) ;
if numel(unique([C{:}])) == 8,
break
else
C = [] ; k = k+1 ;
end
end
celldisp(C)

  1 件のコメント

Jos (10584)
2019 年 2 月 25 日
This comment has nothing to do with my answer ...

サインイン to comment.



Translated by