storing values in a loop

1 visualizzazione (ultimi 30 giorni)
Melissa
Melissa il 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
  3 Commenti
Melissa
Melissa il 21 Nov 2012
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 il 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?

Accedi per commentare.

Risposta accettata

Matt J
Matt J il 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
  1 Commento
Melissa
Melissa il 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 :)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by