필터 지우기
필터 지우기

Why does my loop stop after the first iteration?

조회 수: 8 (최근 30일)
Joseph Weiss
Joseph Weiss 2022년 4월 26일
댓글: Voss 2022년 4월 29일
Hi everyone! I am trying to generate a sample (either a 0 or 1) with certain probability, and then update a Mean formula and Variance formula, both of which are recursive. I will keep generating samples and keep updating the formulas until this condition is met:
if (n>10) && ((Mn_A(A,n)-2*sqrt(Vn_A(A,n)/n)>.05) || (Mn_A(A,n)+2*sqrt(Vn_A(A,n)/n) < 0.5))
disp(['95% confidence interval achieved for A with N = ' num2str(n) ' and width = ' num2str(WidthA)])
break
end
I am getting an error however. It goes through the loop on the n=1 iteration with no problem, but on n=2, I get this error:
Not enough input arguments.
Error in ee497ca2_1>Mn_A (line 14)
if n == 0
Error in ee497ca2_1>Mn_A (line 19)
r = (Mn_A(n-1) + (x1 - Mn_A(n-1)))/n;
Error in ee497ca2_1 (line 4)
Mn_A(A,n)
I think I am missing something on how recursion works, but I am not sure. Here is the whole code below. Thank you!
samples = 500;
for n = 1:samples
A = randsrc(1,1,[0,1;0.49,0.51]);
Mn_A(A,n)
Vn_A(A,n)
ConfidenceInterval_Min_A = Mn_A(A,n) - 2*sqrt(Vn_A(A,n)/n);
ConfidenceInterval_Max_A = Mn_A(A,n) + 2*sqrt(Vn_A(A,n)/n);
WidthA = ConfidenceInterval_Max_A - ConfidenceInterval_Min_A;
if (n>10) && ((Mn_A(A,n)-2*sqrt(Vn_A(A,n)/n)>.05) || (Mn_A(A,n)+2*sqrt(Vn_A(A,n)/n) < 0.5))
disp(['95% confidence interval achieved for A with N = ' num2str(n) ' and width = ' num2str(WidthA)])
break
end
end
function r = Mn_A(x1,n)
if n == 0
r = 0;
elseif n == 1
r = x1;
else
r = (Mn_A(n-1) + (x1 - Mn_A(n-1)))/n;
end
end
function q = Vn_A(x1,n)
if n == 0
q = 0;
elseif n == 1
q = 0;
else
q = Vn_A(n-1) - Vn_A(n-1)/(n-1) + ((x1-Mn_A(n-1))^2)/n;
end
end

채택된 답변

Voss
Voss 2022년 4월 26일
편집: Voss 2022년 4월 26일
Mn_A takes 2 input arguments, x1 and n:
function r = Mn_A(x1,n)
But later in the function Mn_A, you call Mn_A with one input:
r = (Mn_A(n-1) + (x1 - Mn_A(n-1)))/n;
% ^^^ ^^^ one input each time
When Mn_A is called with one input, it has an error on its first line:
function r = Mn_A(x1,n) % if only x1 is given, n is undefined, so
if n == 0 % there's an error trying to refer to n here
(Same for Vn_A.)
  댓글 수: 4
Joseph Weiss
Joseph Weiss 2022년 4월 27일
Okay. I think I was confusing myself as well haha, but it makes sense after you explained it. Thank you again for your help it is much appreciated!
Voss
Voss 2022년 4월 29일
You're welcome!

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by