draw histogramm of X(i)

1 view (last 30 days)
ad lyn
ad lyn on 25 Aug 2021
Commented: the cyclist on 25 Aug 2021
v=9.91256303526217e-3;
x(1)=3.442619855899;
x(128)=0;
for i=2:128
a(i)=exp(-0.5*x(i-1)^2)+(v/x(i-1));
x(i)=sqrt(-2*log(a(i)))
y(i)=nrmlpdf(x(i))
for i=2:128
zigr(i)=(x(i)/x(i-1))
end
r=x(1);
for i= i:1:128
if i==0
u0 = 2*rand()-1;
if(abs(u0)<zigr(i))
X(i)=u0*x(i);
if(i==0)
X(i) = tail( r);
z(i)=u*x(i);
f0=exp(-0.5*(x(i)^2)-(x(i)^2));
f1=exp(-0.5*(x(i+1)^2)-(x(i+1)^2));
if(f1+rand()*(f0-f1)<1.0)
X(i)=z(i);
end
end
end
end
end
end
hist(X)
  2 Comments
the cyclist
the cyclist on 25 Aug 2021
I don't think we can run your code, because nrmlpdf is not a standard MATLAB function.
Also, you did not actually ask a question. What do you need? Be specific.
the cyclist
the cyclist on 25 Aug 2021
I've edited your code here (mostly lining up the code blocks), and changed your nrmlpdf function into an inline function, for convenience.
nrmlpdf = @(x) exp(-x.^2/2);
v=9.91256303526217e-3;
x(1)=3.442619855899;
x(128)=0;
for i=2:128
a(i)=exp(-0.5*x(i-1)^2)+(v/x(i-1));
x(i)=sqrt(-2*log(a(i)));
y(i)=nrmlpdf(x(i));
for i=2:128
zigr(i)=(x(i)/x(i-1));
end
r=x(1);
for i= i:1:128
if i==0
u0 = 2*rand()-1;
if(abs(u0)<zigr(i))
X(i)=u0*x(i);
if(i==0)
X(i) = tail( r);
z(i)=u*x(i);
f0=exp(-0.5*(x(i)^2)-(x(i)^2));
f1=exp(-0.5*(x(i+1)^2)-(x(i+1)^2));
if(f1+rand()*(f0-f1)<1.0)
X(i)=z(i);
end
end
end
end
end
end
hist(X)
You are getting your error because your code never reaches the line where X is defined. The heart of the problem seems to be where you have a second for loop over the same variable:
for i= i:1:128
This is a very confusing line of code, and certainly doesn't do what you intend. I'm guessing you probably want a second looping variable j, that loops from the current value of i to 128.
But I don't understand the indexing of that section of code, and am not sure which index values should be i, and which should be j.
Furthermore, you have the statement
if i==0
and MATLAB is never going to enter that section, because neither looping variable is ever equal to zero.

Sign in to comment.

Accepted Answer

ad lyn
ad lyn on 25 Aug 2021
actually this the ziggurat method programm for generating gaussians randoms numbers.and what's i'm trying to do is to draw the histogramm of X but i'm reveing this message error .
this is the "nrmlpdf" function
function [ y ] = nrmlpdf( x )
y=exp(-x^2/2);
end

More Answers (1)

Steven Lord
Steven Lord on 25 Aug 2021
Instead of calling hist (whose use is discouraged) use histogram.
And I second the cyclist's question for more information about the difficulty you're experiencing when you try to create the histogram.

Community Treasure Hunt

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

Start Hunting!