-1

I want to generate a N dimensional column vector in matlab, with mean 0.5 ( variance is ok to adjust ) , but I want all numbers to be positive, does anyone know how to do it?

Elle
  • 39
  • 1
  • 2

2 Answers2

0

It depends on the distribution that you want. The rand(v) function generates a uniform random distribution (range [0,1] I believe although I'm not sure if either 0 or 1 are theoretically possible values) in an array with dimensions v.

So if you want a 3x4x5x6 array, you would do

myRandArray = rand([3 4 5 6]);

If you want the upper value to be larger, you could do

myRandArray = maxVal * rand([3 4 5 6]);

Where maxVal is the largest value. And if you want a range minVal to maxVal, then do

myRandArray = minVal + (maxVal - minVal) * rand([3 4 5 6]);

For other distributions (like randn for normal distribution) you can make adjustments to the above, obviously. If you want a "truncated normal distribution" - you may need to start with too many values:

dims = [3 4 5 6];
n = prod( dims );
tooMany = 0.5 + randn(2 * n); % since you want mean = 0.5
tooMany(tooMany < 0) = [];
if numel( tooMany ) > n
  myRandArray = reshape(tooMany(1:n), dims);
end

You can obviously improve on this, but it's a general idea.

For example, you could generate only n values, see how many fail (say m), then generate another m * n / (n - m), and repeat as needed until you have exactly n.

Note that the mean of the final distribution is no longer 0.5 since we cut off the tail. A 'normal distribution' cannot remain 'normal' if you exclude certain values. But then you didn't specify what distribution you wanted...

Floris
  • 45,857
  • 6
  • 70
  • 122
0

You can try this:

E.g. create a vector of 1000 random values drawn from a normal distribution with a mean of 0.5 and a standard deviation of 5.

a = 5;
b = 0.5;
y = a.*randn(1000,1) + b;

To make it positive, then you can delete all the numbers that are negative or zero and generate some more until you got n positive numbers.

Check out here for more info.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • Taking the `abs` makes this very much not a random distribution any more. Of course, neither does removing negative values… but I think the latter is less "damaging" to the part of the distribution that is > 0 – Floris Jan 19 '14 at 04:30
  • 1
    @Floris Year, `abs` is a bad choice. Updated. Thanks. – herohuyongtao Jan 19 '14 at 04:36