How to write a script to test central limit theory

28 ビュー (過去 30 日間)
Sophia McInnes
Sophia McInnes 2022 年 9 月 29 日
回答済み: Steven Lord 2022 年 9 月 29 日
This is the question we were given: Test the central limit theorem by writing a function that rolls a given number of 6-sided dice (using randi() ) and sums the result. Repeat 1000 times and record the result. You should end up with a 1x1000 array of sums. Return the mean, standard deviation, and histogram plot with 15 bins.
[ave, stdev, h] = centrallim(n,seed)
Im pretty new to matlab and am unsure of how write a script that calls to my funtion. I have a function written but I am also unsure if it is correct. This is what I have:
function [ave, stdev, h] = centrallim(n,seed)
rng('default'); %reset the random number generator
rng(seed); %force the seed to be the same everytime for testing purposes
% your code here
for k=1:1000
data(k)=sum(randi(6,n));
end
%h=histogram(???)
h=histogram(data,15);
ave=sum(data)./n;
stdev=std(seed);

回答 (3 件)

David Hill
David Hill 2022 年 9 月 29 日
n=10;
r=sum(randi(6,1000,n),2);
m=mean(r);
s=std(r);
histogram(r,15)
  1 件のコメント
David Hill
David Hill 2022 年 9 月 29 日
[m,s,r]=centrallim(20);%script
histogram(r,15)
function [m, s, r] = centrallim(n)
rng('default');
r=sum(randi(6,1000,n),2);
m=mean(r);
s=std(r);
end

サインインしてコメントする。


Torsten
Torsten 2022 年 9 月 29 日
編集済み: Torsten 2022 年 9 月 29 日
rng('default')
n=10;
r=sum(randi(6,1000,10),2);
m=mean(r);
s=std(r);
hold on
histogram((r-m)/s,15,'Normalization','pdf')
plot(-3:0.01:3,1/(sqrt(2*pi))*exp(-0.5*(-3:0.01:3).^2))
hold off
  1 件のコメント
Sophia McInnes
Sophia McInnes 2022 年 9 月 29 日
I'm still confused because I need a seperate function and script

サインインしてコメントする。


Steven Lord
Steven Lord 2022 年 9 月 29 日
Im pretty new to matlab and am unsure of how write a script that calls to my funtion. I have a function written but I am also unsure if it is correct. This is what I have:
Once you've defined your function, you can call it just like you'd call any function that's included in MATLAB. Call it with some number of output arguments and some number of inputs arguments. Since the signature of your function is:
function [ave, stdev, h] = centrallim(n,seed)
you can call your function with 0, 1, 2, or 3 output arguments and 0, 1, or 2 input arguments. But since your code uses both the input arguments, if you call it with fewer than 2 inputs MATLAB will error as soon as it tries to use the variable named seed (on the second line of the body of your function) only to find that variable hasn't been created yet.
rng('default'); %reset the random number generator
rng(seed); %force the seed to be the same everytime for testing purposes

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by