Generate matrix of a random process with each row using different parameters and no for-loop

조회 수: 1 (최근 30일)
For example, suppose I want to generate 5 different normally distributed vectors with 10 samples each. The first vector will have a mu = 0, sigma = 1, the second a mu = 5, sigma = 3, etc. What I would like to be able to do would be something like the following code:
mu = [0, 3, 2, 5, 1]; sigma = [1, 5, 4, 10, 7]; myDistributions = random('norm', mu, sigma, [5, 10]);
and have it output a 5-by-10 matrix with the first row using parameters mu = 0, sigma = 1; the second row using parameters mu = 3, sigma = 5. etc.
I suspect I'll have to bite the bullet and just use a for-loop if I want to do this, but I'm hoping I've missed something else that can be done for this sort of thing.

채택된 답변

Brendan Hamm
Brendan Hamm 2016년 6월 7일
You can use arrayfun for this:
mu = [0, 3, 2, 5, 1];
sigma = [1, 5, 4, 10, 7];
A = arrayfun(@(x,y) random('norm', x, y, [1, 10]),mu,sigma,'UniformOutput',false)
% Change from a cell to a matrix:
A = cell2mat(A);
  댓글 수: 1
Daniel Kellett
Daniel Kellett 2016년 6월 7일
This was a quicker answer than I expected. Works quite well, and seems I will need to be re-visiting arrayfun and its uses. Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jos (10584)
Jos (10584) 2016년 6월 7일
mu = [0, 3, 2, 5, 1]
sigma = [1, 5, 4, 10, 7]
MyDistributions = cell2mat(arrayfun(@(k) random('norm', mu(k), sigma(k), [1, 10]),(1:numel(mu))','un',0))
  댓글 수: 1
Daniel Kellett
Daniel Kellett 2016년 6월 7일
Hmm, I have certainly been overlooking arrayfun for a number of things it seems. This is very helpful! (However, I am accepting Brendan Hamm's answer since it was easier to read and understand at a glance.)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Financial Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by