Need to speed up the generation of random numbers.

3 次查看(过去 30 天)
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

回答(2 个)

James Tursa
James Tursa 2021-5-17
编辑:James Tursa 2021-5-17
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 2021-5-17
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

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by