Random number gerator problem
2 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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
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).
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!