Need to speed up the generation of random numbers.

5 ビュー (過去 30 日間)
Eleftherios Oikonomopoulos
Eleftherios Oikonomopoulos 2021 年 5 月 17 日
回答済み: DGM 2021 年 5 月 17 日
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 Center および File ExchangeRandom Number Generation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by