```Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to avoid nested for loops
Date: Fri, 2 Jul 2010 07:22:07 +0000 (UTC)
Organization: Carnegie Mellon University
Lines: 35
Message-ID: <i0k42v\$2lg\$1@fred.mathworks.com>
References: <i0jemg\$hka\$1@fred.mathworks.com> <i0jpbo\$97t\$1@fred.mathworks.com>
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 1278055327 2736 172.30.248.38 (2 Jul 2010 07:22:07 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 2 Jul 2010 07:22:07 +0000 (UTC)
Xref: news.mathworks.com comp.soft-sys.matlab:649832

"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <i0jpbo\$97t\$1@fred.mathworks.com>...
> "Volkan " <volkaned@hotmail.com> wrote in message <i0jemg\$hka\$1@fred.mathworks.com>...
> > Hi,
> >
> > I am trying to avoid for loops but I couldn't find an easy solution for the problem below:
> >
> > p1hf = [1,2;3,4];
> > nb = 2; % It might go up to 100 or so need a smarter solution
> > p2hf = zeros(nb, nb, nb, nb);
> > for a=1:nb
> >    for b=1:nb
> >       for c=1:nb
> >          for d=1:nb
> >             p2hf(a,b,c,d) = 2*p1hf(a,b)*p1hf(c,d) - p1hf(a,c)*p1hf(b,d);
> >          end
> >       end
> >    end
> > end
> >
> > p2hf is 4-D. Is there an easy way to avoid these loops?
> >
> > Your help will be greatly appreciated.
> - - - - - - - - -
>   I think this does the same thing, but I'm not sure any time is saved.
>
>  p2hf = reshape(reshape(p1hf,[],1)*reshape(p1hf,1,[]),nb,nb,nb,nb);
>  p2hf = 2*p2hf-permute(p2hf,[1,3,2,4]);
>
> Roger Stafford

Thank you so much Roger. I think you are right about cpu usage. It doesn't really save time when nb > 50.

I tried to run it with nb = 2 ( your algorithm was slightly faster), nb =5 ( mine was slightly faster), nb =75 (mine was much faster), and nb =100 (out of memory).

Your solution is brilliant though. I gained a new perspective to consider when dealing with these kinds of problems. Thank you so much again.
```