MATLAB Answers

How to write a function for a certain number of random numbers

3 views (last 30 days)
Cole Bromfield
Cole Bromfield on 16 Jan 2020
Commented: David Hill on 16 Jan 2020
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.

Answers (2)

David Hill
David Hill on 16 Jan 2020
function out=randint(N)
out=randi(19999,1,N)-10000;
end

  2 Comments

David Hill
David Hill on 16 Jan 2020
Thanks for the comment. Good reason to look at the documentation.
out=randi([-9999,9999],1,N);

Sign in to comment.


Meg Noah
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:
histogram(2*5*rand(1000)-5)
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;
while (~isempty(idx))
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);
end
rsq = sqrt(-2.0.*log(rsq)./rsq);
harvest = vertcat(v1.*rsq, v2.*rsq);
harvest = (harvest-mean(harvest)./std(harvest));
harvest = harvest(1:nvals);
end
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.

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags