필터 지우기
필터 지우기

Error using the randi function

조회 수: 3 (최근 30일)
Tony
Tony 2017년 8월 24일
댓글: Jan 2017년 8월 27일
Here is my code:
function EPS
Score=zeros(1,20);
X=[0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1];
for j=1:20
Dealer=X(randi(numel(X)));
if sum(X)-.5*length(X)==0
Pick=X(randi(numel(X)));
else
if sum(X)>size(X)
Pick=1;
if sum(X)<size(X)
Pick=0;
end
end
end
if Pick==Dealer
Score(j)=1;
end
X=X(X~=Dealer);
end
disp(sum(Score)/20);
end
When I run this I get an error on line 11 (Dealer variable as the for loop is line 10): Error using randi First input must be a positive scalar integer value IMAX, or two integer values [IMIN IMAX] with IMIN less than or equal to IMAX.
If I define X as I did in my code and in my command window type X(randi(numel(X))) I do not get an error.
Why is my code giving me the error if in the command window it is working?
  댓글 수: 3
Walter Roberson
Walter Roberson 2017년 8월 24일
Right. You have multiple equal values so X(X~=Dealer) is deleting multiple entries, all of the duplicates of Dealer. You only have two unique values in X, so after the second time you execute the line you would have deleted everything out of X.
Perhaps you should instead keep track of the random index and delete only that one item.
Tony
Tony 2017년 8월 26일
Thank you guys for your help!

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

채택된 답변

KSSV
KSSV 2017년 8월 24일
Score=zeros(1,20);
X=[0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1];
for j=1:20
idx = randi(numel(X)) ;
Dealer=X(idx);
if sum(X)-.5*length(X)==0
Pick=X(randi(numel(X)));
else
if sum(X)>size(X)
Pick=1;
if sum(X)<size(X)
Pick=0;
end
end
end
if Pick==Dealer
Score(j)=1;
end
X(idx) = [] ;
end
disp(sum(Score)/20);
  댓글 수: 2
Tony
Tony 2017년 8월 26일
Thanks!
Jan
Jan 2017년 8월 27일
if sum(X)<size(X) is tricky: Note that size replies a vector.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by