Step 1:
Let's say that I want to generate discrete uniform random numbers taking the value -1 or 1. So in other words I want to generate numbers having the following distribution:
P(X = -1) = 0.5
P(X = 1) = 0.5
To generate an array of 100 of those numbers I can write this code:
n = 100
DV = [-1,1]; % Discrete value
RI = unidrnd(2,n,1); % Random uniform index
DUD = DV(RI); % Discrete uniform distribution
My DUD array looks like: [-1,1,1,1,-1,-1,1,-1,...]
Step 2:
Now I would like to generate 10 numbers equal to sum(DUD)
, so 10 numbers having a distribution corresponding to the sum of 100 numbers following a discrete uniform distribution.
Of course I can do that:
for ii = 1:10
n = 100;
DV = [-1,1]; % Discrete value
RI = unidrnd(2,n,1); % Random index
DUD = DV(RI); % Discrete uniform distribution
SDUD(ii) = sum(DUD);
end
With
SDUD =
2 2 -6 -2 -4 2 4 4 0 2
Is there a mathematical/matlab trick to do that ? without using a for loop.
The histogram of SDUD (with 10000 values and n=100) looks like this:
Bonus:
It will be great if the original discrete values could be modified. So instead of [-1,1] the discrete value could be, for example, [0,1,2], each with an occurence p = 1/number_of_discrete_value, so 1/3 in this example.
For two values
That's essentially a binomial distribution (see Matlab's binornd
), only scaled and shifted because the underlying values are given by DV
instead of being 0
and 1
:
n = 100;
DV = [-1 1];
p = .5; % probability of DV(2)
M = 10;
SDUD = (DV(2)-DV(1))*binornd(n, p, M, 1)+DV(1)*n;
For an arbitrary number of values
What you have is a multinomial distribution (see Matlab's mnrnd
):
n = 100;
DV = [-2 -1 0 1 2];
p = [.1 .2 .3 .3 .1]; % probability of each value. Sum 1, same size as DV
M = 10;
SDUD = sum(bsxfun(@times, DV, mnrnd(n, p, M)), 2);
In general the sum of independent variables has pdf equal to the convolution of the pdfs of the summand variables. When the variables are discrete, the convolution is very conveniently computed via the Matlab function conv
(which probably calls fft
for a fast, exact calculation).
When the pdf's are uniform, then the result of the convolution is a binomial or multinomial pdf. But the convolution stuff applies for non-uniform pdfs as well.
来源:https://stackoverflow.com/questions/52389357/how-to-generate-a-number-representing-the-sum-of-a-discrete-uniform-distribution