1 view (last 30 days)

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

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

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.

Opportunities for recent engineering grads.

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

Start Hunting!
## 1 Comment

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/519611-create-a-random-array-with-certain-requirements#comment_832314

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/519611-create-a-random-array-with-certain-requirements#comment_832314

Sign in to comment.