Create a random array with certain requirements

1 view (last 30 days)
luca
luca on 21 Apr 2020
Edited: Muthu on 21 Apr 2020
Hi,
I would like to create an array V that contains random elements (numbers) with the following characteristic:
1) The array should have lenght equal to X
2) The avarage value of the elements inside the array should be Y
3) The elements should stay inside an interval T= [A to B]
4) The elements should not necessary be integer, could also be decimal till up to the fourth decimal place.
Let's consider the following example:
GIven as inputs: X= 10 , Y=19.9948 , T= [0 to 50]
I would like to obtain a random array like
V = [1 5.5674 28.9764 18 30.8433 35.3389 4.6333 10 16 49.5887]
Thanks for your help
  1 Comment
luca
luca on 21 Apr 2020
With something like that I Create a vector of 10 random values drawn from a normal distribution with a mean of 15 and a standard deviation of 20.But some values are out of the range [0 50]. As it possible to see from y.
a = 20;
b = 15;
y = a.*randn(10,1) + b;
Do you know how I can change the code, so that it works?

Sign in to comment.

Answers (1)

Muthu
Muthu on 21 Apr 2020
Edited: Muthu on 21 Apr 2020
Hello Luca,
I have tried to draft a program which does just the requested function.
You can still expand and fine tune this program with more condtions.
function res_array = random_array(x, y, interval)
temp_array = rand(1,x) * interval(2);
temp_mean = mean(temp_array);
add_to_sum = x * (y-temp_mean);
add_in_each_term = add_to_sum / x ;
res_array = temp_array + add_in_each_term ;
end
result = random_array(10,19.9948,[0,50])
result =
37.1853 7.8636 35.8637 7.3257 41.6126 12.6486 4.9792 7.7036 25.9517 18.8139
  4 Comments
luca
luca on 21 Apr 2020
I suppose n is equal to X. In any case, with this code sometimes I obtain something negative like this:
Columns 1 through 8
30.4070 2.6201 27.5111 2.3479 11.5966 24.4533 32.1837 -2.7714
Columns 9 through 10
39.6417 31.9580
Do you know how to solve this problem?
Muthu
Muthu on 21 Apr 2020
n is X, its a mistake.
The negative value is because of the subtraction from Y:
add_to_sum = x * (y-temp_mean);
add_in_each_term = add_to_sum / x ;
res_array = temp_array + add_in_each_term ;
when temp_mean is more than Y, we get negative value to add to sum.
hence that in turn is subtracted from all terms in res_array. When the random number generated is less than the value subtracted, we get negative i suppose.
It is a very good point to start adding conditions further in the function to get the proper result array.

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!