Why does my loop stop after the first iteration?
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Voss
le 26 Avr 2022
Modifié(e) : Voss
le 26 Avr 2022
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Calendar dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!