














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!















This document is a supplemental reference for M ATLAB functions described in the text Prob- ability and Stochastic Processes: A Friendly Introduction for Electrical and Computer Engineers. This document should be accompanied by matcode.zip, an archive of the corresponding M AT- LAB .m files. Here are some points to keep in mind in using these functions.
bernoullipmf y=bernoullipmf(p,x)
function pv=bernoullipmf(p,x) %For Bernoulli (p) rv X %input = vector x %output = vector pv %such that pv(i)=Prob(X=x(i)) pv=(1-p)(x==0) + p(x==1); pv=pv(:);
Input: p is the success probability of a Bernoulli random variable X , x is a vector of possible sample values Output: y is a vector with y(i) = PX (x(i)).
bernoullicdf y=bernoullicdf(p,x)
function cdf=bernoullicdf(p,x) %Usage: cdf=bernoullicdf(p,x) % For Bernoulli (p) rv X, %given input vector x, output is %vector pv such that pv(i)=Prob[X<=x(i)] x=floor(x(:)); allx=0:1; allcdf=cumsum(bernoullipmf(p,allx)); okx=(x>=0); %x_i < 1 are bad values x=(okx.x); %set bad x_i= cdf= okx.allcdf(x); %zeroes out bad x_i
Input: p is the success probability of a Bernoulli random variable X , x is a vector of possible sample values Output: y is a vector with y(i) = F (^) X (x(i)).
bernoullirv x=bernoullirv(p,m)
function x=bernoullirv(p,m) %return m samples of bernoulli (p) rv r=rand(m,1); x=(r>=(1-p));
Input: p is the success probability of a Bernoulli random variable X , m is a positive integer vector of possible sample values Output: x is a vector of m independent sample values of X
binomialpmf y=binomialpmf(n,p,x)
function pmf=binomialpmf(n,p,x) %binomial(n,p) rv X, %input = vector x %output= vector pmf: pmf(i)=Prob[X=x(i)] if p<0. pp=p; else pp=1-p; end i=0:n-1; ip= ((n-i)./(i+1))(pp/(1-pp)); pb=((1-pp)ˆn)cumprod([1 ip]); if pp < p pb=fliplr(pb); end pb=pb(:); % pb=[P[X=0] ... P[X=n]]ˆt x=x(:); okx =(x>=0).(x<=n).(x==floor(x)); x=okx.x; pmf=okx.pb(x+1);
Input: n and p are the parameters of a binomial ( n , p ) random vari- able X , x is a vector of possible sample values Output: y is a vector with y(i) = PX (x(i)).
binomialrv x=binomialrv(n,p,m)
function x=binomialrv(n,p,m) % m binomial(n,p) samples r=rand(m,1); cdf=binomialcdf(n,p,0:n); x=count(cdf,r);
Input: n and p are the parameters of a binomial ran- dom variable X , m is a positive integer Output: x is a vector of m independent samples of random variable X
bivariategausspdf
function f=bivariategausspdf(muX,muY,sigmaX,sigmaY,rho,x,y) %Usage: f=bivariategausspdf(muX,muY,sigmaX,sigmaY,rho,x,y) %Evaluate the bivariate Gaussian (muX,muY,sigmaX,sigmaY,rho) PDF nx=(x-muX)/sigmaX; ny=(y-muY)/sigmaY; f=exp(-((nx.ˆ2) +(ny.ˆ2) - (2rhonx.ny))/(2(1-rhoˆ2))); f=f/(2pisigmaxsigmaysqrt(1-rhoˆ2));
Input: Scalar parameters muX,muY,sigmaX,sigmaY,rho of the bivariate Gaussian PDF, scalars x and y.
Output: f the value of the bivariate Gaussian PDF at x,y.
duniformcdf y=duniformcdf(k,l,x)
function cdf=duniformcdf(k,l,x) %Usage: cdf=duniformcdf(k,l,x) % For discrete uniform (k,l) rv X % and input vector x, output is % vector cdf: cdf(i)=Prob[X<=x(i)] x=floor(x(:)); %for noninteger x_i allx=k:max(x); %allcdf = cdf values from 0 to max(x) allcdf=cumsum(duniformpmf(k,l,allx)); %x_i < k are zero prob values okx=(x>=k); %set zero prob x(i)=k x=((1-okx)k)+(okx.x); %x(i)=0 for zero prob x(i) cdf= okx.*allcdf(x-k+1);
Input: k and l are the parameters of a discrete uniform ( k , l ) random variable X , x is a vector of pos- sible sample values Output: y is a vector with y(i) = F (^) X (x(i)).
duniformpmf y=duniformpmf(k,l,x)
function pmf=duniformpmf(k,l,x) %discrete uniform(k,l) rv X, %input = vector x %output= vector pmf: pmf(i)=Prob[X=x(i)] pmf= (x>=k).(x<=l).(x==floor(x)); pmf=pmf(:)/(l-k+1);
Input: k and l are the parameters of a discrete uniform ( k , l ) ran- dom variable X , x is a vector of possible sample values Output: y is a vector with y(i) = PX (x(i)).
duniformrv x=duniformrv(k,l,m)
function x=duniformrv(k,l,m) %returns m samples of a discrete %uniform (k,l) random variable r=rand(m,1); cdf=duniformcdf(k,l,k:l); x=k+count(cdf,r);
Input: k and l are the parameters of a discrete uniform ( k , l ) random variable X , m is a positive integer Output: x is a vector of m independent samples of random variable X
exponentialpdf y=exponentialpdf(lambda,x)
function f=exponentialpdf(lambda,x) f=lambdaexp(-lambdax); f=f.*(x>=0);
Input: lambda is the parameter of an ex- ponential random variable X , vector x Output: Vector y such that yi = f (^) X ( x (^) i ) = λ e −λ x^ i^.
exponentialrv x=exponentialrv(lambda,m)
function x=exponentialrv(lambda,m) x=-(1/lambda)*log(1-rand(m,1));
Input: lambda is the parameter of an expo- nential random variable X , integer m Output: Length m vector x such that each x (^) i is a sample of X
finitecdf y=finitecdf(sx,p,x)
function cdf=finitecdf(s,p,x) % finite random variable X: % vector sx of sample space % elements {sx(1),sx(2), ...} % vector px of probabilities % px(i)=P[X=sx(i)] % Output is the vector % cdf: cdf(i)=P[X=x(i)] cdf=[]; for i=1:length(x) pxi= sum(p(find(s<=x(i)))); cdf=[cdf; pxi]; end
Input: sx is the range of a finite random variable X , px is the corresponding probability as- signment, x is a vector of possible sample values Output: y is a vector with y(i) = F (^) X (x(i)).
finitecoeff rho=finitecoeff(SX,SY,PXY)
function rho=finitecoeff(SX,SY,PXY); %Usage: rho=finitecoeff(SX,SY,PXY) %Calculate the correlation coefficient rho of %finite random variables X and Y ex=finiteexp(SX,PXY); vx=finitevar(SX,PXY); ey=finiteexp(SY,PXY); vy=finitevar(SY,PXY); R=finiteexp(SX.SY,PXY); rho=(R-exey)/sqrt(vx*vy);
Input: Grids SX, SY and probability grid PXY de- scribing the finite ran- dom variables X and Y. Output: rho, the correlation coefficient of X and Y
finitecov covxy=finitecov(SX,SY,PXY)
function covxy=finitecov(SX,SY,PXY); %Usage: cxy=finitecov(SX,SY,PXY) %returns the covariance of %finite random variables X and Y %given by grids SX, SY, and PXY ex=finiteexp(SX,PXY); ey=finiteexp(SY,PXY); R=finiteexp(SX.SY,PXY); covxy=R-exey;
Input: Grids SX, SY and probability grid PXY describing the finite random variables X and Y. Output: covxy, the covariance of X and Y.
finiteexp ex=finiteexp(sx,px)
function ex=finiteexp(sx,px); %Usage: ex=finiteexp(sx,px) %returns the expected value E[X] %of finite random variable X described %by samples sx and probabilities px ex=sum((sx(:)).*(px(:)));
Input: Probability vector px, vector of samples sx describing random variable X. Output: ex, the expected value E [ X ].
finitepmf y=finitepmf(sx,p,x)
function pmf=finitepmf(sx,px,x) % finite random variable X: % vector sx of sample space % elements {sx(1),sx(2), ...} % vector px of probabilities % px(i)=P[X=sx(i)] % Output is the vector % pmf: pmf(i)=P[X=x(i)] pmf=zeros(size(x(:))); for i=1:length(x) pmf(i)= sum(px(find(sx==x(i)))); end
Input: sx is the range of a finite random variable X , px is the corresponding probability assignment, x is a vector of possible sample values Output: y is a vector with y(i) = P [ X = x(i)].
finiterv x=finiterv(sx,p,m)
function x=finiterv(s,p,m) % returns m samples % of finite (s,p) rv %s=s(:);p=p(:); r=rand(m,1); cdf=cumsum(p); x=s(1+count(cdf,r));
Input: sx is the range of a finite random variable X , p is the corresponding probability assignment, m is positive integer Output: x is a vector of m sample values y(i) = F (^) X (x(i)).
gaussvector x=gaussvector(mu,C,m)
function x=gaussvector(mu,C,m) %output: m Gaussian vectors, %each with mean mu %and covariance matrix C if (min(size(C))==1) C=toeplitz(C); end n=size(C,2); if (length(mu)==1) mu=muones(n,1); end [U,D,V]=svd(C); x=V(Dˆ(0.5))randn(n,m)... +(mu(:)ones(1,m));
Input: For a Gaussian (μ X , C (^) X ) random vector X , gaussvector can be called in two ways:
If mu is a length n vector, then mu is the ex- pected value vector; otherwise, each element of X is assumed to have mean mu. Output: n × m matrix x such that each column x(:,i) is a sample vector of X
gaussvectorpdf f=gaussvector(mu,C,x)
function f=gaussvectorpdf(mu,C,x) n=length(x); z=x(:)-mu(:); f=exp(-z’inv(C)z)/... sqrt((2pi)ˆndet(C));
Input: For a Gaussian (μ X , C (^) X ) random vec- tor X , mu is a length n vector, C is the n × n covariance matrix, x is a length n vector. Output: f is the Gaussian vector PDF f X ( x ) evaluated at x.
geometriccdf y=geometriccdf(p,x)
function cdf=geometriccdf(p,x) % for geometric(p) rv X, %For input vector x, output is vector %cdf such that cdf_i=Prob(X<=x_i) x=(x(:)>=1).*floor(x(:)); cdf=1-((1-p).ˆx);
Input: p is the parameter of a geometric random variable X , x is a vector of possible sample values Output: y is a vector with y(i) = F (^) X (x(i)).
geometricpmf y=geometricpmf(p,x)
function pmf=geometricpmf(p,x) %geometric(p) rv X %out: pmf(i)=Prob[X=x(i)] x=x(:); pmf= p((1-p).ˆ(x-1)); pmf= (x>0).(x==floor(x)).*pmf;
Input: p is the parameter of a geometric random variable X , x is a vector of possible sample values Output: y is a vector with y(i) = PX (x(i)).
geometricrv x=geometricrv(p,m)
function x=geometricrv(p,m) %Usage: x=geometricrv(p,m) % returns m samples of a geometric (p) rv r=rand(m,1); x=ceil(log(1-r)/log(1-p));
Input: p is the parameters of a geometric random variable X , m is a positive integer Output: x is a vector of m inde- pendent samples of random variable X
icdfrv x=icdfrv(@icdf,m)
function x=icdfrv(icdfhandle,m) %Usage: x=icdfrv(@icdf,m) %returns m samples of rv X %with inverse CDF icdf.m u=rand(m,1); x=feval(icdfhandle,u);
Input: @icdfrv is a “handle” (a kind of pointer) to a M ATLAB function icdf.m that is M ATLAB ’s representation of an inverse CDF F X −^1 ( x ) of a random variable X , inte- ger m Output: Length m vector x such that each x (^) i is a sample of X
pascalrv x=pascalrv(k,p,m)
function x=pascalrv(k,p,m) % return m samples of pascal(k,p) rv r=rand(m,1); rmax=max(r); xmin=k; xmax=ceil(2(k/p)); %set max range sx=xmin:xmax; cdf=pascalcdf(k,p,sx); while cdf(length(cdf)) <=rmax xmax=2xmax; sx=xmin:xmax; cdf=pascalcdf(k,p,sx); end x=xmin+countless(cdf,r);
Input: k and p are the parameters of a Pas- cal random variable X , m is a posi- tive integer Output: x is a vector of m independent samples of random variable X
phi y=phi(x)
function y=phi(x) sq2=sqrt(2); y= 0.5 + 0.5*erf(x/sq2);
Input: Vector x Output: Vector y such that y(i) = (x(i)).
poissoncdf y=poissoncdf(alpha,x)
function cdf=poissoncdf(alpha,x) %output cdf(i)=Prob[X<=x(i)] x=floor(x(:)); sx=0:max(x); cdf=cumsum(poissonpmf(alpha,sx)); %cdf from 0 to max(x) okx=(x>=0);%x(i)<0 -> cdf= x=(okx.x);%set negative x(i)= cdf= okx.cdf(x+1); %cdf=0 for x(i)<
Input: alpha is the parameter of a Poisson (α) random variable X , x is a vector of possible sample values Output: y is a vector with y(i) = F (^) X (x(i)).
poissonpmf y=poissonpmf(alpha,x)
function pmf=poissonpmf(alpha,x) %Poisson (alpha) rv X, %out=vector pmf: pmf(i)=P[X=x(i)] x=x(:); k=(1:max(x))’; logfacts =cumsum(log(k)); pb=exp([-alpha; ... -alpha+ (klog(alpha))-logfacts]); okx=(x>=0).(x==floor(x)); x=okx.x; pmf=okx.pb(x+1); %pmf(i)=0 for zero-prob x(i)
Input: alpha is the parameter of a Poisson (α) random variable X , x is a vector of possible sample val- ues Output: y is a vector with y(i) = PX (x(i)).
poissonrv x=poissonrv(alpha,m)
function x=poissonrv(alpha,m) %return m samples of poisson(alpha) rv X r=rand(m,1); rmax=max(r); xmin=0; xmax=ceil(2alpha); %set max range sx=xmin:xmax; cdf=poissoncdf(alpha,sx); %while ( sum(cdf <=rmax) ==(xmax-xmin+1) ) while cdf(length(cdf)) <=rmax xmax=2xmax; sx=xmin:xmax; cdf=poissoncdf(alpha,sx); end x=xmin+countless(cdf,r);
Input: alpha is the parameter of a Poisson (α) random vari- able X , m is a positive inte- ger Output: x is a vector of m inde- pendent samples of random variable X
uniformcdf y=uniformcdf(a,b,x)
function F=uniformcdf(a,b,x) %Usage: F=uniformcdf(a,b,x) %returns the CDF of a continuous %uniform rv evaluated at x F=x.((x>=a) & (x<b))/(b-a); F=f+1.0(x>=b);
Input: a and ( b) are parameters for continuous uniform random variable X , vector x Output: Vector y such that yi = F (^) X ( x (^) i )
brownian w=brownian(alpha,t)
function w=brownian(alpha,t) %Brownian motion process %sampled at t(1)<t(2)< ... t=t(:); n=length(t); delta=t-[0;t(1:n-1)]; x=sqrt(alphadelta).gaussrv(0,1,n); w=cumsum(x);
Input: t is a vector holding an ordered se- quence of inspection times, alpha is the scaling constant of a Brownian motion process such that the i th in- crement has variance α( ti − ti − 1 ). Output: w is a vector such that w(i) is the position at time t(i) of the par- ticle in Brownian motion.
cmcprob pv=cmcprob(Q,p0,t)
function pv = cmcprob(Q,p0,t) %Q has zero diagonal rates %initial state probabilities p K=size(Q,1)-1; %max no. state %check for integer p if (length(p0)==1) p0=((0:K)==p0); end R=Q-diag(sum(Q,2)); pv= (p0(:)’expm(Rt))’;
Input: n × n state transition matrix Q for a continuous-time finite Markov chain, length n vector p0 denoting the initial state proba- bilities, nonengative scalar t Output: Length n vector pv such that pv(t) is the state probability vector at time t of the Markov chain Comment: If p0 is a scalar integer, then the sim- ulation starts in state p
cmcstatprob pv=cmcstatprob(Q)
function pv = cmcstatprob(Q) %Q has zero diagonal rates R=Q-diag(sum(Q,2)); n=size(Q,1); R(:,1)=ones(n,1); pv=([1 zeros(1,n-1)]*Rˆ(-1))’;
Input: State transition matrix Q for a continuous- time finite Markov chain Output: pv is the stationary probability vector for the continuous-time Markov chain
dmcstatprob pv=dmcstatprob(P)
function pv = dmcstatprob(P) n=size(P,1); A=(eye(n)-P); A(:,1)=ones(n,1); pv=([1 zeros(1,n-1)]*Aˆ(-1))’;
Input: n × n stochastic matrix P representing a discrete-time aperiodic irreducible finite Markov chain Output: pv is the stationary probability vector.
poissonarrivals s=poissonarrivals(lambda,T)
function s=poissonarrivals(lambda,T) %arrival times s=[s(1) ... s(n)] % s(n)<= T < s(n+1) n=ceil(1.1lambdaT); s=cumsum(exponentialrv(lambda,n)); while (s(length(s))< T), s_new=s(length(s))+ ... cumsum(exponentialrv(lambda,n)); s=[s; s_new]; end s=s(s<=T);
Input: lambda is the arrival rate of a Poisson process, T marks the end of an observation interval [ 0 , T ]. Output: s=[s(1), ..., s(n)]’ is a vector such that s(i) is i th arrival time. Note that length n is a Poisson random variable with expected value λ T. Comment: This code is pretty stupid. There are decidedly better ways to create a set of arrival times; see Prob- lem 10.13.5.
poissonprocess N=poissonprocess(lambda,t)
function N=poissonprocess(lambda,t) %input: rate lambda>0, vector t %For a sample function of a %Poisson process of rate lambda, %N(i) = no. of arrivals by t(i) s=poissonarrivals(lambda,max(t)); N=count(s,t);
Input: lambda is the arrival rate of a Pois- son process, t is a vector of “inspec- tion times’.’ Output: N is a vector such that N(i) is the number of arrival by inspection time t(i).
simcmc ST=simcmc(Q,p0,T)
function ST=simcmc(Q,p0,T); K=size(Q,1)-1; max no. state %calc average trans. rate ps=cmcstatprob(Q); v=sum(Q,2); R=ps’v; n=ceil(0.6T/R); ST=simcmcstep(Q,p0,2*n); while (sum(ST(:,2))<T), s=ST(size(ST,1),1); p00=Q(1+s,:)/v(1+s); S=simcmcstep(Q,p00,n); ST=[ST;S]; end n=1+sum(cumsum(ST(:,2))<T); ST=ST(1:n,:); %truncate last holding time ST(n,2)=T-sum(ST(1:n-1,2));
Input: state transition matrix Q for a continuous-time finite Markov chain, vector p0 denoting the ini- tial state probabilities, integer n Output: A simulation of the Markov chain system over the time interval [ 0 , T ]: The output is an n × 2 matrix ST such that the first column ST(:,1) is the sequence of system states and the second column ST(:,2) is the amount of time spent in each state. That is, ST(i,2) is the amount of time the system spends in state ST(i,1). Comment: If p0 is a scalar integer, then the simula- tion starts in state p0. Note that n , the number of state occupancy periods, is random.
count n=count(x,y)
function n=count(x,y) %Usage n=count(x,y) %n(i)= # elements of x <= y(i) [MX,MY]=ndgrid(x,y); %each column of MX = x %each row of MY = y n=(sum((MX<=MY),1))’;
Input: Vectors x and y Output: Vector n such that n ( i ) is the number of elements of x less than or equal to y(i).
countequal n=countequal(x,y)
function n=countequal(x,y) %Usage: n=countequal(x,y) %n(j)= # elements of x = y(j) [MX,MY]=ndgrid(x,y); %each column of MX = x %each row of MY = y n=(sum((MX==MY),1))’;
Input: Vectors x and y Output: Vector n such that n ( i ) is the number of elements of x equal to y(i).
countless n=countless(x,y)
function n=countless(x,y) %Usage: n=countless(x,y) %n(i)= # elements of x < y(i) [MX,MY]=ndgrid(x,y); %each column of MX = x %each row of MY = y n=(sum((MX<MY),1))’;
Input: Input: Vectors x and y Output: Vector n such that n ( i ) is the number of elements of x strictly less than y(i).
dftmat F=dftmat(N)
function F = dftmat(N); Usage: F=dftmat(N) %F is the N by N DFT matrix n=(0:N-1)’; F=exp((-1.0j)2pi(n(n’))/N);
Input: Integer N. Output: F is the N by N discrete Fourier trans- form matrix
freqxy fxy=freqxy(xy,SX,SY)
function fxy = freqxy(xy,SX,SY) %Usage: fxy = freqxy(xy,SX,SY) %xy is an m x 2 matrix: %xy(i,:)= ith sample pair X,Y %Output fxy is a K x 3 matrix: % [fxy(k,1) fxy(k,2)] % = kth unique pair [x y] and % fxy(k,3)= corresp. rel. freq.
%extend xy to include a sample %for all possible (X,Y) pairs: xy=[xy; SX(:) SY(:)]; [U,I,J]=unique(xy,’rows’); N=hist(J,1:max(J))-1; N=N/sum(N); fxy=[U N(:)]; %reorder fxy rows to match %rows of [SX(:) SY(:) PXY(:)]: fxy=sortrows(fxy,[2 1 3]);
Input: For random variables X and Y , xy is an m × 2 matrix holding a list of sample values pairs; yy(i,:) is the i th sample pair ( X , Y ). Grids SX and SY represent- ing the sample space. Output: fxy is a K × 3 matrix. In each row
[fxy(k,1) fxy(k,2) fxy(k,3)] [fxy(k,1) fxy(k,2)] is a unique ( X , Y ) pair with relative frequency fxy(k,3). Comment: Given the grids SX, SY and the probability grid PXY, a list of random sample value pairs xy can be simulated by the commands S=[SX(:) SY(:)]; xy=finiterv(S,PXY(:),m); The output fxy is ordered so that the rows match the ordering of rows in the matrix [SX(:) SY(:) PXY(:)].
fftc S=fftc(r,N); S=fftc(r)
function S=fftc(varargin); %DFT for a signal r %centered at the origin %Usage: % fftc(r,N): N point DFT of r % fftc(r): length(r) DFT of r r=varargin{1}; L=1+floor(length(r)/2); if (nargin>1) N=varargin{2}(1); else N=(2L)-1; end R=fft(r,N); n=reshape(0:(N-1),size(R)); phase=2pi(n/N)(L-1); S=R.exp((1.0j)phase);
Input: Vector r=[r(1) ... r(2k+1)] holding the time sequence r − k ,... , r 0 ,... , r (^) k centered around the origin. Output: S is the DFT of r Comment: Supports the same calling conventions as fft.