user1729448
user1729448

Reputation: 149

Matlab random number range

I am struggling generating a random number within the range of x.

So say x is 4 the range would be -2 to 2 and if it was 6 then -3 to 3.

I know it is

rand() * something + somethingelse

Upvotes: 1

Views: 157

Answers (2)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

From where you left it is not hard to find the solution:

rand() * something + somethingelse

From left to right:

rand() : From 0 to 1

We want to make the range 4 times as wide, so we do:

rand()*4 : From 0 to 4

Now the width is correct, we just need to give it the correct location:

rand()*4-2: From -2 to 2

Upvotes: 1

Werner
Werner

Reputation: 2557

You have to take out the mean of rand*x, that is x/2:

x = [1 2 3 4 5 6 7]
rand(1,numel(x)).*x-x/2

ans =

    0.4172   -0.4283    0.7716    1.0149   -0.5978    0.4069   -2.9690

Upvotes: 1

Related Questions