convert vector into 'matrix equivalent'

I have a vector of binomially distributed random numbers from i = 0 to n eg R = [0 1 2 1 4]'
I want to convert this this into a matrix of dimensions length( R ) by n where each row contains either zeros or ones. The number of ones required in each row is taken from the equivalent value in R. Otherwise values are zero. I would like the position of the ones within each row to be random. For instance, if R above and n = 5 then one matrix would be S = [ 0 0 0 0 0; 0 0 1 0 0; 0 1 1 0 0; 0 0 1 0 0; 1 1 1 0 1]
In practice,R is large with 1e6 values so I need the operation to be as fast as possible.
Many thanks!

1 件のコメント

Matt J
Matt J 2016 年 10 月 9 日
In practice,R is large with 1e6 values
If m=length( R ) what are the typical magnitudes of both m and n?

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

 採用された回答

Walter Roberson
Walter Roberson 2016 年 10 月 9 日

1 投票

[~, permidx] = sort( rand(length(R), n), 2);
S = permidx <= repmat(R(:),1,n);

1 件のコメント

J T
J T 2016 年 10 月 9 日
Thank you very much!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeRandom Number Generation についてさらに検索

質問済み:

J T
2016 年 10 月 9 日

コメント済み:

J T
2016 年 10 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by