MATLAB Answers

Need to speed up the generation of random numbers.

41 views (last 30 days)
Eleftherios Oikonomopoulos
Answered: DGM on 17 May 2021
Hi to all,
I have a 4-D array A of size 81x81x120x120. Each element of this array is an integer with values between 0 and 5.
Now for each element of this array, I need to generate as many random numbers as the value of the element.
For example, if A(1, 1, 1, 1) = 5, I must generate 5 random numbers.
I have tried this approach with the arrayfun:
C = arrayfun(@(x) rand(x, 1), A, 'UniformOutput', false);
where the output is a cell array of the same size as A and each cell contains as many random numbers as the integer value of the corresponding element of A.
Now this approach works, but it's too slow for the purposes of my problem, since I need to run this 500 times.
Is there any way to speed it up?
Thank you very much!
Best,
Eleftherios

Answers (2)

James Tursa
James Tursa on 17 May 2021
Edited: James Tursa on 17 May 2021
You could over generate a large matrix and then pick off the number of elements you need later. E.g.,
C = rand([5 size(A)]);
Then e.g. for the (1,1,1,1) spot:
n = A(1,1,1,1);
r = C(1:n,1,1,1,1);
In general for the i,j,k,m spot:
n = A(i,j,k,m);
r = C(1:n,i,j,k,m);
etc.

DGM
DGM on 17 May 2021
At least in my tests, this is somewhat faster:
n = 10;
A = randi(5,n,n,n); % generate test array
rv = rand(sum(A(:)),1); % generate all random numbers
C = reshape(mat2cell(rv,A(:),1),size(A)); % form a cell array out of them

Community Treasure Hunt

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

Start Hunting!