Hi,
What is the fastest way to create a matrix containing random integers: 1 or
-1 with equal probability?
I have tried the following options but was wondering if I am missing
something.
(I also need 1, 0 or -1 with different probabilities later, which is why I
don't just use a boolean random matrix.)
Thanks,
David.
julia> function rand_pm1_matrix(L)
matrix::Array{Int8, 2} = 2 .* randbool(L,L) .- 1
end
rand_pm1_matrix (generic function with 1 method)
julia> function elementwise(L)
A = Array(Int8, (L, L))
for i in 1:length(A)
if rand() < 0.5
A[i] = -1
else
A[i] = 1
end
end
A
end
elementwise (generic function with 1 method)
julia> function elementwise_random_block(L)
r = rand(L, L)
A = Array(Int8, (L, L))
for i in 1:length(A)
if r[i] < 0.5
A[i] = -1
else
A[i] = 1
end
end
A
end
elementwise_random_block (generic function with 1 method)
julia> L = 10
10
julia> rand_pm1_matrix(L);
julia> elementwise(L);
julia> elementwise_random_block(L);
julia>
julia> L = 100
100
julia> @time rand_pm1_matrix(L);
elapsed time: 6.5661e-5 seconds (188588 bytes allocated)
julia> @time elementwise(L);
elapsed time: 0.001172332 seconds (10160 bytes allocated)
julia> @time elementwise_random_block(L);
elapsed time: 0.000131455 seconds (90240 bytes allocated)
julia>
julia> L = 1000
1000
julia> @time rand_pm1_matrix(L);
elapsed time: 0.013428217 seconds (18125456 bytes allocated)
julia> @time elementwise(L);
elapsed time: 0.074257183 seconds (1000176 bytes allocated)
julia> @time elementwise_random_block(L);
elapsed time: 0.007721683 seconds (9000288 bytes allocated)
julia>
julia> L = 10000
10000
julia> @time rand_pm1_matrix(L);
elapsed time: 2.75006866 seconds (1812500448 bytes allocated)
julia> @time elementwise(L);
elapsed time: 6.727148454 seconds (100000176 bytes allocated)
julia> @time elementwise_random_block(L);
elapsed time: 2.819847794 seconds (900000288 bytes allocated)
\