storing values in a loop

1 次查看(过去 30 天)
Melissa
Melissa 2012-11-21
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
  3 个评论
Melissa
Melissa 2012-11-21
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(i)=Nf+1;
else
Nf(i)=Nf;
end
pf(i)=Nf(i)/N;
end
John Petersen
John Petersen 2012-11-21
These lines look like problematic
Nf(i) = Nf+1;
Nf(i) = Nf;
Maybe you want to index the Nf on both sides?

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2012-11-21
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
  1 个评论
Melissa
Melissa 2012-11-21
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 :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by