Path: news.mathworks.com!not-for-mail From: <HIDDEN> Newsgroups: comp.soft-sys.matlab Subject: Re: Is it possible to convert this for loop into a matrix? Date: Mon, 27 Dec 2010 21:58:05 +0000 (UTC) Organization: The MathWorks, Inc. Lines: 53 Message-ID: <ifb25d$ihh$1@fred.mathworks.com> References: <ifavqc$jha$1@fred.mathworks.com> <wG7So.18696$My1.7287@newsfe16.iad> Reply-To: <HIDDEN> NNTP-Posting-Host: webapp-03-blr.mathworks.com Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: fred.mathworks.com 1293487085 18993 172.30.248.38 (27 Dec 2010 21:58:05 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Mon, 27 Dec 2010 21:58:05 +0000 (UTC) X-Newsreader: MATLAB Central Newsreader 2141479 Xref: news.mathworks.com comp.soft-sys.matlab:698469 My mistake. There is only one threshold. I'm not sure why I had threshold1 and threshold2, they are the same. Do you have any pointers as to how I can vectorize f,f1,and f2? f = constant*(x+y)*(1/x+1/y) f1 = exp(V_max(x,y)) and V_max is the local maximum of a non-linear algebraic function of x and y? Thanks for your quick response. Walter Roberson <roberson@hushmail.com> wrote in message <wG7So.18696$My1.7287@newsfe16.iad>... > On 27/12/10 3:18 PM, Haoyang Liu wrote: > > I have the following for loop: > > > > N=5000; > > a=rand(N,1); %in the actual program, this is not rand, but rand would do > > for now > > b=rand(N,1); > > c=zeros(N); > > for i = 1:N > > for j = 1:N > > if a(i)+b(j) >= threshold1 > > d=f1(a(i),b(j)); > > elseif a(i)+b(j) <= threshold2 > > d=f2(a(i),b(j)); > > end > > c(i,j)=f(a(i),b(j))/d; > > end > > end > > > > This takes a very very long time to run. I'd like to be able to speed it > > up via using matrix operation or other means. I should note that the > > inline functions in the above code are non-linear functions of x and y. > > Essentially I need to populate the matrix with a function whose input > > depends on the position of matrix in reference to another vector. > > > > Any help is greatly appreciated. > > a_b = bsxfun(@plus, a, b.'); > f1pos = a_b >= threshold1; > f2pos = ~f1pos & a_b <= threshold2 > fab = bsxfun(@f, a, b.'); > f1ab = bsxfun(@f1, a, b.'); > f2ab = bsxfun(@f2, a, b'); > fab(f1pos) = fab(f1pos) ./ f1ab(f1pos); > fab(f2pos) = fab(f2pos) ./ f2ab(f2pos); > fab(~(f1pos | f2pos)) = NaN; > > The NaN corresponds to the fact that you have not defined d for the case > where the sum does not fall within either threshold. > > Probably the performance could be improved -- if f or f1 or f2 can be > vectorized, or if there is no third undefined possibility.