How to write a function for a certain number of random numbers
2 views (last 30 days)
My assignment says:
"Create an .m file that is a function that creates an array of N random integers in the range from -9999 to 9999. It should be in the form of x=randint(N)."
But I have no idea how to do that. I've tried everything. This is due in 4 days.
Meg Noah on 16 Jan 2020
If the numbers are supposed to be uniformly distributed, then they are between 0 and 1. So just linearly scale the value 0 to the minimum and value 1 to the maximum. Subtract 0.5 to make it zero mean. Multiply by the range (max-min). If the result supposed to have a 0 mean (which your example does), then the offset needs to adjusted. The min after doing that will be -range*0.5. Add range*0.5 and subtract the minvalue. For example, a histogram of 1000 points between -5 and 5 is:
If you want a normal distribution, and you don't have the statistics toolbox, you have to write your own. This will do:
function [harvest] = getRandomGaussianDistribution(nvals)
N = ceil(nvals/2);
v1 = rand(N,1);
v2 = rand(N,1);
idx = 1:N;
v1(idx) = rand(numel(idx),1);
v2(idx) = rand(numel(idx),1);
v1(idx) = 2*v1(idx) - 1;
v2(idx) = 2*v2(idx) - 1;
rsq = v1.^2 + v2.^2;
idx = find(rsq >= 1.0 | rsq <= 0);
rsq = sqrt(-2.0.*log(rsq)./rsq);
harvest = vertcat(v1.*rsq, v2.*rsq);
harvest = (harvest-mean(harvest)./std(harvest));
harvest = harvest(1:nvals);
Then you have to search and exclude outliars because of the nature of statistics. Normalization is done by subtracting the mean and dividing by the standard deviation.