```Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Avoiding for loops
Date: Wed, 4 May 2011 11:25:20 +0000 (UTC)
Organization: California Institute of Technology
Lines: 37
Message-ID: <iprd30\$h9q\$1@fred.mathworks.com>
References: <ipmm71\$p7b\$1@fred.mathworks.com> <ipo9s4\$rkm\$1@fred.mathworks.com>
NNTP-Posting-Host: www-04-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1304508320 17722 172.30.248.35 (4 May 2011 11:25:20 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 4 May 2011 11:25:20 +0000 (UTC)
Xref: news.mathworks.com comp.soft-sys.matlab:725161

"Roger Stafford" wrote in message <ipo9s4\$rkm\$1@fred.mathworks.com>...
> "Lan" wrote in message <ipmm71\$p7b\$1@fred.mathworks.com>...
> > Is there a way to vectorize the for loop below? How can I use normpdf with a vector input?
> >
> > z0 is a n x 1 vector (n=2000)
> >
> > for n=1:length(z0)
> >     X=-100:2/100:100;
> >     Y=X.*normpdf(X,(0.6*z0(n)),0.64);
> >     M0(n) = trapz(X,Y);
> > end
> >
> > Thanks
> - - - - - - - - -
>   If your aim is to vectorize this precise computation, I'm afraid it would involve some 2000 by 10001 size matrices which could give you memory troubles.  You could make use of 'ndgrid' for this purpose, but I won't write out the explicit expression because I seriously doubt that this is what you really want to do.
>
>   I am guessing you are using 'trapz' to approximate the integral of the above expression for Y between -100 and +100 for each of the mean values in mu = 0.6*z0.  If that is the case, you can easily obtain a vectorized solution involving all z0 in terms of the 'normpdf' and 'normcdf' functions.  It would look like this:
>
>  M0 = -sigma^2*(normpdf(b,mu,sigma)-normpdf(a,mu,sigma)) ...
>       + mu.*(normcdf(b,mu,sigma)-normcdf(a,mu,sigma));
>
> where mu = 0.6*z0, sigma = 0.64, b = 100, and a = -100.  There would then be no need for involving all those ten thousand and one values in X.
>
>   You can derive this by writing the expression for integrand Y as:
>
>  x*normpdf(x,mu,sigma) = (x-mu)*normpdf(x,mu,sigma) + mu*normpdf(x,mu,sigma)
>
> The first of these terms can easily be integrated to -sigma^2 times just 'normpdf', while the integral of the second can be evaluated in terms of the cumulative normal distribution values, 'normcdf'.  (You had better check my algebra and calculus here for possible mistakes, but I think the basic method is correct.)
>
> Roger Stafford

Thanks!

But do I understand it correctly that I still have to loop over the length of z0? since my mu changes for each element of z0. I want to obtain a vector M0 of dimensions 2000x 1.

Lan

```