Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Avoiding for loops
Date: Tue, 3 May 2011 07:12:04 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 29
Message-ID: <ipo9s4$rkm$1@fred.mathworks.com>
References: <ipmm71$p7b$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-06-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1304406724 28310 172.30.248.38 (3 May 2011 07:12:04 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 3 May 2011 07:12:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:724922

"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