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 CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by