Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: find vector r<=p (p: a given vector)
Date: Mon, 24 Nov 2008 00:23:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 50
Message-ID: <ggcs55$aiv$1@fred.mathworks.com>
References: <gf2ppf$q6l$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1227486181 10847 172.30.248.37 (24 Nov 2008 00:23:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 24 Nov 2008 00:23:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:502698


"Oriole " <oriole_ni@hotmail.com> wrote in message <gf2ppf$q6l$1@fred.mathworks.com>...
> Hello, 
> 
> I am asking questions again...
> 
> I want to find all (vector) solutions for r<=p (component by component), where r, p are n-dimensional vectors, p is given, r is the unknown vector. 
> 
> In other words, find all vector r=(r_1, r_2, ...r_n) satisfying r_1 <=p_1, r_2 <=p_2, ... r_n <=p_n. 
> 
> 
> Here is my code for this:
> 
> n=length(p)
> R=[];
> r= zeros(1,n);
> flag =1;
> while  flag ==1   
>     R = [R;r];
>     flag =0;
>     for j= n:-1:1
>         if r(j)+1 <= p(j)
>             r(j+1:n) =0;
>             r(j) = r(j)+1;
>             flag = 1;
>             break
>         end
>     end
> end
> 
> 
> It does the job, but since I am not very experienced in Matlab, I wonder whether there're better ways than this double loop. Maybe there are some built-in functions that I should take adavantage of ?
> 
> Thank you for your advice!
> Oriole

  Just for variety's sake here is a for-loop method, Oriole.  It should be much faster than your double loop.  Bruno's vectorized solution is certainly more elegant-looking and could well be even faster.

 n = length(p);
 d = max(floor(p),0);
 R = (0:d(n))';
 s = d(n)+1;
 for k = n-1:-1:1
  R = repmat(R,d(k)+1,1);
  t = repmat(0:d(k),s,1);
  s = s*(d(k)+1);
  R = [t(:),R];
 end

Roger Stafford