Andrea
Andrea

Reputation: 125

How generate multiple random distribution from a vector of mean and st.dev in octave/matlab?

So I have a vector V of values with dimension [5,1]. For each value in this vector V[i] I would like to generate let's say 5 numbers normally distributed with mean V[i] and a fixed st deviation. So in the end I will have a matrix [5,5] which on the i-row has 5 values normally distributed with mean V[i]. How can i do this with octave/matlab without using for loop ? Practically I would like to pass to the normrnd function a vector of means V and get a set of n normally distributed number for each mean in the vector V.

Upvotes: 2

Views: 1094

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112749

Using normrnd with array input

You can turn the vector of means into a matrix and pass it to normrnd. This works because, as explained in normrnd's documentation,

r = normrnd(mu,sigma) [...]

To generate random numbers from multiple distributions, specify mu and sigma using arrays. If both mu and sigma are arrays, then the array sizes must be the same. If either mu or sigma is a scalar, then normrnd expands the scalar argument into a constant array of the same size as the other argument. Each element in r is the random number generated from the distribution specified by the corresponding elements in mu and sigma.

Example:

mu = [30; 15; 7; -60; 0]; % vector of means
std = 2;                  % common standard deviation
N = 4;                    % number of samples for each mean
result = normrnd(repmat(mu(:), 1, N), std);

Using randn with implicit expansion

You can generate a matrix with samples from a standard Gaussian distribution, mutiply by the desired standard deviation, and add the desired mean to each row:

result = mu(:) + std*randn(numel(mu), N);

This works because

  • changing the standard deviation of a zero-mean Gausian distribution is equivalent to scaling;
  • changing the mean of a Gaussian distribution is equivalent to shifting.

The shifting is done using implicit expansion. This approach avoids building the intermediate matrix of repeated means from the previous approach, and calls randn instead of normrnd, so it may be more efficient.

Upvotes: 4

Related Questions