Create matrix with randomly distributed integers, with exact relative abundances

3 ビュー (過去 30 日間)
Christopher
Christopher 2014 年 10 月 14 日
コメント済み: Thorsten 2014 年 10 月 14 日
I want to create a matrix of randomly distributed integers between 0 and 4 (0, 1, 2, 3, or 4). However, I want the abundance of each integer to conform to a predetermined value.
So if I have a vector of abundances (e.g.):
% 0 1 2 3 4 <--corresponding random numbers
mo = [0 0.5533 0.1346 0.1167 0.1954]; % abundance of random
numbers
and I want to fill up a matrix:
P = zeros(100,100);
I can see that the abundances should be
abund = round(mo.*size(P,1).*size(P,2));
= 0 5533 1346 1167 1954
But how do I fill up the matrix P with these randomly distributed numbers? The important thing is that the abundances are exactly as predetermined.

回答 (1 件)

Thorsten
Thorsten 2014 年 10 月 14 日
編集済み: Thorsten 2014 年 10 月 14 日
values = [0:4];
mo = [0 0.5533 0.1346 0.1167 0.1954];
a = 100; b = 100;
% create a vector where each value appears mo(i)*a*b times
P = [];
for i = 1:numel(mo)
P = [P values(i)*ones(1, round(a*b*mo(i)))];
end
% randomize and reshape
P = P(randperm(a*b));
P = reshape(P, [a b]);
% check
hi = hist(P(:), [0:4])
  2 件のコメント
Christopher
Christopher 2014 年 10 月 14 日
編集済み: Christopher 2014 年 10 月 14 日
almost correct, but the algorithm fails if i set a=120 and b=120. The array becomes 14399 elements instead of the correct 14400, so reshape fails. Can this be fixed easily?
Edit: sorry the problem is that my vector 'mo' has more decimal places. Is there a way to ensure that the correct size vector for P results (a*b) for any real numbers in the vector 'mo' (as long as mo sums to 1)?
Thorsten
Thorsten 2014 年 10 月 14 日
P = [];
for i = 1:numel(mo)-1
P = [P values(i)*ones(1, round(a*b*mo(i)))];
end
P(end+1:a*b) = values(end);

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

カテゴリ

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