Reputation: 125
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
Reputation: 112749
normrnd
with array inputYou 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
andsigma
using arrays. If bothmu
andsigma
are arrays, then the array sizes must be the same. If eithermu
orsigma
is a scalar, thennormrnd
expands the scalar argument into a constant array of the same size as the other argument. Each element inr
is the random number generated from the distribution specified by the corresponding elements inmu
andsigma
.
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);
randn
with implicit expansionYou 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
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