# storing values in a loop

7 views (last 30 days)
Melissa on 21 Nov 2012
I have a function of the following and it only gives the last value. I want to see a vector of Nf and pf. I tried inserting i. For example Nf(i)=Nf and received the following error:
Attempted to access Nf(2); index out of bounds because numel(Nf)=1.
Error in probabilitycounter (line 23) Nf(i)=Nf
Here is what I have written to produce actual data:
function [Nf,pf]= probabilitycounter(N,mu_x,mu_y,sig_x,sig_y)
%Starting value of Nf
Nf=0;
%Creating a loop to generate pf and Nf
for i=1:N
%Random variable declaration for ux and uy
u_x=rand(1,1);
u_y=rand(1,1);
%Normal Inverse
x=norminv(u_x,mu_x,sig_x)
y=norminv(u_y,mu_y,sig_y)
%Starting Nf and pf Calculation
if (x-y>0)
Nf=Nf+1;
else
Nf=Nf;
end
pf=Nf/N;
end
John Petersen on 21 Nov 2012
These lines look like problematic
Nf(i) = Nf+1;
Nf(i) = Nf;
Maybe you want to index the Nf on both sides?

Matt J on 21 Nov 2012
I'm guessing this might be what you want:
function [Nf,pf]= probabilitycounter(N,mu_x,mu_y,sig_x,sig_y)
%Starting value of Nf
Nf=zeros(1,N);
%Creating a loop to generate pf and Nf
for i=2:N
%Random variable declaration for ux and uy
u_x=rand(1,1);
u_y=rand(1,1);
%Normal Inverse
x=norminv(u_x,mu_x,sig_x)
y=norminv(u_y,mu_y,sig_y)
%Starting Nf and pf Calculation
if (x-y<0)
Nf(i)=Nf(i-1)+1;
else
Nf(i)=Nf(i-1);
end
pf(i)=Nf(i)/N;
end
Melissa on 21 Nov 2012
Ah so the dimensions were wrong thats why you used the zeros matrix? then had to reset the index? thank you that is exactly what I needed. I really appreciate your help :)