Search code examples
performancematlabcell

Generating arrays of random numbers without loop in MATLAB


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.


Solution

  • 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