Set specific standard deviation limit on randn matrix?
21 次查看(过去 30 天)
显示 更早的评论
I want to create a randn matrix, but I want all the values to be within 2 standard deviations away from the mean.
So I make the randn(a,b) matrix, but I'm confused as to how to set the limit of the standard deviation when creating the matrix itself.
0 个评论
回答(3 个)
Wayne King
2013-10-9
With the Statistics Toolbox:
pd = makedist('Normal','mu',0,'sigma',2);
t = truncate(pd,0,4);
% generate the random matrix - here 100x100
R = random(t,100,100);
The above truncates to [0,4], if you want [-2*sd,2*sd]
t = truncate(pd,-4,4);
R = random(t,100,100);
6 个评论
Walter Roberson
2013-10-9
Wayne used the new-fangled random() call, not randn().
Truncation is quite new, either this new release or the prior one if I recall.
Walter Roberson
2013-10-9
Are you aware that numbers generated by such a system will never be randomly distributed? The Normal distribution inherently requires infinite distribution.
If you generate by randn(), you can discard values whose abs() > 2, but beware that the result will not be normally distributed and will not have a standard distribution of 1.
2 个评论
Walter Roberson
2013-10-9
No, you cannot do that. You will need to keep creating values until you have enough for your purpose. For example instead of generating 10 values, generate 15, throw out the ones that are out of range, and see if you are left with at least 10; if not, then generate again, but if so then return the first 10.
Roger Stafford
2013-10-9
编辑:Roger Stafford
2013-10-9
(Since you say 'randn' the mean will be zero and the standard deviation one.) You will have to call on 'randn' for more elements than you wish to have in your final matrix so as to select those which satisfy your condition.
x = [];
n = 0;
while n<a*b
t = randn(ceil(1.03*(a*b-n)),1);
x = [x;t(t<2)];
n = length(x);
end
x = reshape(x(1:a*b),a,b);
To not exceed two standard deviations if you use 1.03 above, you will usually have to go through the while-loop only once. With a looser condition, the multiplicative factor needs to be greater.
EDIT:
To accomplish this task for arbitrary mean, mu, and standard deviation sigma, replace the last line by:
x = sigma*reshape(x(1:a*b),a,b)+mu;
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!