0

I have a vector that is defined by a=[1000 1000 1000 1000 1000];. I am asked to add uniform noise in the interval [-9,9], but the still save the sum of all elements at 5000. How can I do that? Thanks in advance.

A Doe
  • 301
  • 2
  • 14
  • 1
    Possible duplicate of [Random numbers that add to 100: Matlab](https://stackoverflow.com/questions/8064629/random-numbers-that-add-to-100-matlab) – Ralf Stubner Sep 18 '18 at 09:45

2 Answers2

2

You can add uniform random noise with rand. From the Matlab documentation:

In general, you can generate N random numbers in the interval (a,b) with the formula r = a + (b-a).*rand(N,1).

vec = [1000 1000 ... 1000];
noise = -9 + 18 * rand(size(vec));

Then you need to center the noise around 0:

noise = noise - mean(noise);

Finally, you add it to the initial vector:

vec = vec + noise;

For example:

>> vec = [1000 1000 1000 1000 1000];
>> noise = -8 + 18 * rand(size(vec));       
>> vec_noise = vec + noise - mean(noise)

vec_noise =

   1.0e+03 *

    1.0002    0.9968    1.0021    0.9988    1.0020

>> sum(vec_noise)

ans =

        5000
TwistedSim
  • 1,960
  • 9
  • 23
  • 1
    Your Matlab quote left off "a" or substituded "vec" for "a". s/b: `a + (b-a).*rand(N,1)` – doug Sep 18 '18 at 03:01
  • 3
    There is a chance that, after centering the noise around 0, the values are no longer in the selected interval. I think this needs a rejection scheme. – Cris Luengo Sep 18 '18 at 05:00
  • Yes I agree, this is only an approximation for large number of samples. – TwistedSim Sep 18 '18 at 12:38
1

I know its not an elegant way, but you can draw noise for every vector element in a loop, check the sum of previous noise and possible max and min of remaining noises. If your current noise + sum of previous noise would exceed possible remaining range, draw again (in new range). The last element's noise must be set to get noise sum equal to zero.

p.osinski
  • 23
  • 4
  • 1
    _The last element's noise must be set to get noise sum equal to zero._ But that spoils the "uniform noise" requirement: not all (vectored-valued) samples will have the same probability; see [here](https://stackoverflow.com/q/8064629/2586922) – Luis Mendo Sep 18 '18 at 10:36