1

I have a loop which generates random samples from the chi-square distribution with different degrees of freedom (df1, df2, df3, df4) and saves it to a cell array:

for k=1:N
x{k} = chi2rnd([df1 df2 df3 df4]);
end

Is there any way to do this without any iterations? I tried to use cellfun, but it didn't work.

1 Answer 1

2

Here is a vectorized way (method 1):

x = num2cell(chi2rnd(repmat([df1 df2 df3 df4], N, 1), N, 4), 2);

You may also try this method (method 2):

df = [df1 df2 df3 df4];
y = zeros(N,numel(df));
for k = 1:numel(df)
  y(:,k) = chi2rnd(df(k),N,1);
end
x = num2cell (y,2);

Result of timing for N = 10000 in Octave. However you need to measure the time in MATLAB:

Original solution :              3.91095 seconds
Vectorized solution (method 1):  0.0691321 seconds
Loop solution (method 2) :       0.0124869 seconds
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.