How to write a script to test central limit theory

28 vues (au cours des 30 derniers jours)
Sophia McInnes
Sophia McInnes le 29 Sep 2022
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);

Réponses (3)

David Hill
David Hill le 29 Sep 2022
n=10;
r=sum(randi(6,1000,n),2);
m=mean(r);
s=std(r);
histogram(r,15)
  1 commentaire
David Hill
David Hill le 29 Sep 2022
[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

Connectez-vous pour commenter.


Torsten
Torsten le 29 Sep 2022
Modifié(e) : Torsten le 29 Sep 2022
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 commentaire
Sophia McInnes
Sophia McInnes le 29 Sep 2022
I'm still confused because I need a seperate function and script

Connectez-vous pour commenter.


Steven Lord
Steven Lord le 29 Sep 2022
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

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by