How i can call a function 100 time?

조회 수: 3 (최근 30일)
Hydro
Hydro 2014년 9월 11일
댓글: Image Analyst 2014년 9월 11일
Here is what i need to call 100 times and then record result in a vector
function [r] = dieroll(n)
r=0; % Number of time the dice been rolled
Y = 0;
% n = sum of the rolls
while Y<n;
r=r+1;
Y = Y+randi(6,1);
end
end
  댓글 수: 1
Joseph Cheng
Joseph Cheng 2014년 9월 11일
function [r] = dieroll(n)
r=0; % Number of time the dice been rolled
Y = 0; % n = sum of the rolls
while Y<n;
r=r+1;
Y = Y+randi(6,1);
end
end
for simple reading. next time highlight the coded portion and click on the {}code button so it is easier to read. Check the preview to see that it does read well too.
Look at the documentation for while and for loops. the documentation there should be enough to get you where you need to go. what you have now is 90% there.

댓글을 달려면 로그인하십시오.

답변 (3개)

Rick Rosson
Rick Rosson 2014년 9월 11일
for k = 1:100
...
...
end

Image Analyst
Image Analyst 2014년 9월 11일
To call dieroll() a hundred times, try this:
r = zeros(1,100);
n = 3; % Whatever you want...
% Toss 3 dice 100 times and sum the result and store in r.
for tossNumber = 1 : 100
r(tossNumber) = dieroll(n);
end
function y = dieroll(n)
% Roll die n times and sum the result.
y = sum(randi(6, 1, n));

Joseph Cheng
Joseph Cheng 2014년 9월 11일
so in your private message you clearied by :
thanks for the comment. Here is what i tried however, its not working. I acutally need to write another function which will call the posted function 100 times. then i need to record the result and do some descriptive statistics.
function [r] = dieroll(n)
for Y = 1:10000;
r=0; % Number of time the dice been rolled
Y = 0; % n = sum of the rolls
while Y<n;
r=r+1;
Y = Y+randi(6,1);
end
end
end
so this still doesn't negate looking at the the documentation. since you need to call the dieroll function and store it in array i'll leave this here http://blogs.mathworks.com/pick/2007/08/20/matlab-basics-video/ create another function similar to dieroll
function results = Ndieroll(Ntimes)
for roll =1:Ntimes
......
end
end
by following what was given for the assignment ("create another function") you should be creating another function.
  댓글 수: 2
Hydro
Hydro 2014년 9월 11일
Thanks Joseph, it was helpful. really appreciated
Image Analyst
Image Analyst 2014년 9월 11일
Exactly what function were you hoping to call 100 times? dieroll() (like I assumed), or randi()?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by