Random number gerator problem
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
James Tursa
2015-8-5
编辑:James Tursa
2015-8-5
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 个评论
James Tursa
2015-8-5
编辑:James Tursa
2015-8-5
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).
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!