Problem with average of random numbers generated within a boundary, the average exceeds the boundaries after a certain point.

2 次查看(过去 30 天)
I wrote a code that generates random numbers within a boundary, c times, and then calculates the average of those random c numbers. After this first iteration of c, it repeats the same process for c+1. When graphed c values with respect to average values, the following graph occured. There are two problems, why in the first iteration, at c=1, are all the values close to 0? Also, when number of iterations c increases, the average of randoms also increase. Here are the results when a=32, b=46 and c=99999.
My hypothesis is that a problem occured in for loop, but really dont know what and how it did happen. In case you want to try the code yourself here it is:
%% the initial ones
% a represents minimum interval, b represenets max interval, c represents
% number of iterations
a=32;
b=46;
c=99999;
%% allocation of vectors
RoI=zeros(1,c);
final =zeros(1,c); %#ok<PREALL>
%% iterations and creation of final vector
for ii= 1:c
randoms= a+(b-a)*rand(ii,1);
% as ii increases the number of random iterations increase
AtimesAverageNumber= (sum(randoms))/c;
% this function finds the average value of the iteration
RoI(ii)= AtimesAverageNumber;
% generates the results of iterations in a vector
end
final = [1:c; RoI];
% generates the final vector that will be used in plotting
%% plotting the values of the final vector
plot(final(1,:),final(2,:))
What is the problem and how can I fix it? Thanks for your answers!

回答(1 个)

Bala Tripura Bodapati
Hi Ege Artan,
It is my understanding that you are able to calculate and plot the average values but the average values are out of boundary. The average values are out of the boundary limits because in the average calculation, the denominator should be the number of random numbers generated rather than number of iterations. The following code is the entire code snipped attached with the plot output:
%% the initial ones
% a represents minimum interval, b represents max interval, c represents
% number of iterations
a=32;
b=46;
c=99999;
%% allocation of vectors
RoI=zeros(1,c);
final =zeros(1,c); %#ok<PREALL>
%% iterations and creation of final vector
for ii= 1:c
randoms= a+(b-a)*rand(ii,1);
% as ii increases the number of random iterations increase
AtimesAverageNumber= (sum(randoms))/ii; %Modified to find out the average
% this function finds the average value of the iteration
RoI(ii)= AtimesAverageNumber;
% generates the results of iterations in a vector
end
final = [1:c; RoI];
% generates the final vector that will be used in plotting
%% plotting the values of the final vector
plot(final(1,:),final(2,:))
Please refer to the rand documentation for more information.

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by