필터 지우기
필터 지우기

Index exceeds matrix dimensions

조회 수: 2 (최근 30일)
Chris
Chris 2011년 11월 6일
clear
clc
count_eight=0;
clear
clc
count_eight=0;
RandStream.setDefaultStream = (RandStream('mt19937ar','seed',sum(100*clock)));
roll=input('Enter number of rolls \n');
for rolling = 1:roll
dice1 = randi(6);
dice2 = randi(6);
end
if dice1+dice2==8
count_eight=count_eight+1;
end
fprintf('Percentage of times an 8 appeared %.1f ',count_eight(roll*100));
display('End of Program')
roll=input('Enter number of rolls \n');
for rolling = 1:roll
dice1 = randi(6);
dice2 = randi(6);
end
if dice1+dice2==8
count_eight=count_eight+1;
end
fprintf('Percentage of times an 8 appeared %.1f ',count_eight(roll*100));
display('End of Program')
ERROR MESSAGE:
??? Index exceeds matrix dimensions.
Error in ==> Homework10 at 51
fprintf('Percentage of times an 8 appeared
%.1f ',count_eight(roll*100));

채택된 답변

Image Analyst
Image Analyst 2011년 11월 6일
Well at least you made a good attempt at it. but count_eight is a scalar while you try to print it out as an array in your fprintf. Try it this way:
clear;
clc;
count_eight=0;
RandStream.setDefaultStream = (RandStream('mt19937ar','seed',sum(100*clock)));
response = inputdlg('Enter number of rolls \n');
roll = str2double(response{1});
for rolling = 1:roll
dice1 = randi(6);
dice2 = randi(6);
if dice1+dice2==8
count_eight=count_eight+1;
end
end
message = sprintf('8 appeared %d times in %d rolls = %.2f%%', ...
count_eight, roll, count_eight/roll*100);
uiwait(msgbox(message));

추가 답변 (2개)

Sven
Sven 2011년 11월 6일
It's just a small typo, I think:
fprintf('Percentage of times an 8 appeared %.1f ',count_eight(roll*100));
should be:
fprintf('Percentage of times an 8 appeared in %.1f percent of rolls',count_eight/roll*100);
Let me clarify though: The error is caused by a typo. Note however that I don't think the program does what you intend.
Where you have written:
for rolling = 1:roll
dice1 = randi(6);
dice2 = randi(6);
end
if dice1+dice2==8
count_eight=count_eight+1;
end
Notice that you are only checking if dice one and two add up to 8 after the loop through many dice has finished. Ie, you're only checking once!
I think you want:
for rolling = 1:roll
dice1 = randi(6);
dice2 = randi(6);
if dice1+dice2==8
count_eight=count_eight+1;
end
end
There is, however, an even better way of doing that. This way is very "MATLABBY" because it doesn't use loops:
dice1 = randi(6,roll,1);
dice2 = randi(6,roll,1);
count_eight = sum(dice1+dice2 == 8);

Chris
Chris 2011년 11월 7일
Thanks for the advice guys.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by