Forums

Negative Random number generation

Started by Ishtiaque Ahmed March 2, 2008
Hello,
I need to generate random numbers, for example, in the range -20 to 20 or -150 to 150 or so for 1200 points.
How can I do this using 'rand' function in matlab??

I got one way to do this from this forum, like:
a = unifrnd (-2 , 2 , [1024,1]);

and, it was said that rand is equivalent to unifrnd. So, I tried with rand but the warning says:
Warning: Input arguments must be scalar.
a Empty array: 0-by-2-by-1024
Also when I tried with unifrnd, I got: ??? Undefined command/function 'unifrnd'.

Hope to get some solutions from you. Thanks.
Hello,
*******************
the mistake that you made while running the command unifrnd is that you used brackets, namely [ ]. So, instead of running

a = unifrnd (-20 , 20 , [1024,1]);

run

a = unifrnd (-20 , 20 , 1024, 1);
*******************
Alternatively, a clever way to generate uniformly distributed random numbers in the interval [-20,20], using rand and randn is the following

clear all

N = 1024;

a = 20 * rand(N,1) .* sign(randn(N,1));

plot(a)
***************
Another way to do the same thing, except using only the command rand is the following:

clear all

N = 1000;

a = 20 * rand(N,1) .* sign(rand(N,1) - 0.5);

plot(a)
***************

Manolis C. Tsakiris
You have to generate always number between 0 and 1 (using rand) then you
have to adjust the result to match the specific request.

Example
You want to generate random number uniform distributed between -10 and 10,
for example a vector of dimension 1,N

1) use rand function

out_1 = rand(1,N); % [0 ->1]

2) Shift

out_2 = out_1 - 0.5; % [-0.5 -> 0.5]

3) Amplification

out_3 = out_2 * 20; % [-10 -> 10]
If you want, these operations can be collapsed in a function that you ca
call as you like e.g. unifrnd

On Fri, Feb 29, 2008 at 6:26 PM, Ishtiaque Ahmed
wrote:

> Hello,
> I need to generate random numbers, for example, in the range -20 to 20 or
> -150 to 150 or so for 1200 points.
> How can I do this using 'rand' function in matlab??
>
> I got one way to do this from this forum, like:
> a = unifrnd (-2 , 2 , [1024,1]);
>
> and, it was said that rand is equivalent to unifrnd. So, I tried with rand
> but the warning says:
> Warning: Input arguments must be scalar.
> a > Empty array: 0-by-2-by-1024
> Also when I tried with unifrnd, I got: ??? Undefined command/function
> 'unifrnd'.
>
> Hope to get some solutions from you. Thanks.
>
>