How about

In  [186]: @time rand(-1:2:1,10000,10000);
elapsed time: 2.29940616 seconds (800000224 bytes allocated)

No need for an extra function. This uses a range from -1 to 1 with a step
size of 2 so you only get those two numbers.

-Jacob


On Mon, Mar 24, 2014 at 7:21 PM, David P. Sanders <[email protected]>wrote:

> 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)
>
> \
>

Reply via email to