Why does my loop stop after the first iteration?
Show older comments
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
Accepted Answer
More Answers (0)
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!