Star
Star

Reputation: 2299

Generate three dimensional arrays using mvnrnd in Matlab?

I need to generate a three dimensional matrix B in Matlab using the command mvnrnd. In particular, let

mu=[0 0; -1 -3; 0 4; 2 4; 8 1]

and

sigma=repmat(1/(3^2)*eye(2),[1,1,5])

If I use the command

B= mvnrnd(mu,sigma)

I get a matrix 5x2 in which each row i is sampled from N(mu(i,:), sigma(:,:,i)). Instead, I want B to be 5x2xr, i.e. each row iis sampled from N(mu(i,:), sigma(:,:,i)) r times.

Upvotes: 1

Views: 279

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

You can do as follows:

  1. Repeat mu along 1st dimension and sigma along 3rd dimension by a factor of r and feed them to mvnrnd. That way you get the desired number of samples, but the r matrices are stacked along 1st dimension, instead of along 3rd dimension as desired.
  2. Then play with dimensions to put into desired form.

Code:

B = mvnrnd(repmat(mu, [r 1]), repmat(sigma, [1 1 r])); %// step 1
B = permute(reshape(B.', size(mu,2), size(mu,1), r), [2 1 3]);  %'// step 2

Upvotes: 1

Related Questions