Random number gerator problem

6 views (last 30 days)
Sanwal Yousaf
Sanwal Yousaf on 5 Aug 2015
Edited: James Tursa on 5 Aug 2015
The question that i am working on is as follows
Write a function called randomness that takes three input arguments: limit, n, and m, in that order. The function returns an n-by-m matrix of uniformly distributed random integers between 1 and limit inclusive. You are not allowed to use randi, but you can use rand. You will also find the built-in function floor useful for obtaining integers. To make sure that your result is indeed uniformly distributed, test the output of the function by using the built-in function hist, which plots a histogram.
My code is as follows,
function [r] = randomness(limit,n,m)
r= 1+floor(rand(n,m).*(limit-1))
hist(randomness, 1:limit)
end
It keeps giving me an error for the arguments (20,500000,1) and i am not sure why.I have tried using ceil and fix instead of floor, but to little or no avail.

Accepted Answer

James Tursa
James Tursa on 5 Aug 2015
Edited: James Tursa on 5 Aug 2015
hist(r, 1:limit);
You inadvertently used randomness in your hist call, so MATLAB tried a recursive call with no arguments, hence the error.
You should re-check your algorithm, however, since it currently doesn't produce any values at "limit" and the instructions say "inclusive".
  2 Comments
Sanwal Yousaf
Sanwal Yousaf on 5 Aug 2015
Edited: Sanwal Yousaf on 5 Aug 2015
basically the arguments that i am testing it at are (20,500000,1)because that is where it breaks down. The limit in this case would be 20. WHen i plot this histogram, it comes up something like this which is indicative of the fact that not every number has equal probability of popping up with the same occurence.
James Tursa
James Tursa on 5 Aug 2015
Edited: James Tursa on 5 Aug 2015
You should not expect a random sampling to produce the exact number of samples in each bin. But for a large enough sample you can expect the numbers to be reasonably close. There are other tests you can apply to see if your results are in fact "reasonably close", but I think all your instructor wanted was a quick visual check hence the suggestion to use hist. In that sense your chart looks like a pretty good result to me EXCEPT THAT 20 IS MISSING! So, as stated above, your current algorithm is not producing numbers from 1 to 20 "inclusive". You need to look into the reason for this and fix your algorithm. (It's a relatively easy fix ... but I will let you find it).

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!