Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: minimise range of vector
Date: Sat, 31 Jan 2009 17:39:01 +0000 (UTC)
Organization: Loughborough University
Lines: 30
Message-ID: <gm22bl$acj$1@fred.mathworks.com>
References: <gm08oh$16q$1@fred.mathworks.com> <gm0dei$f2s$1@fred.mathworks.com> <gm0eee$imn$1@fred.mathworks.com> <gm0haa$jal$1@fred.mathworks.com> <gm1kol$fd6$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 1233423541 10643 172.30.248.37 (31 Jan 2009 17:39:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sat, 31 Jan 2009 17:39:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1338633
Xref: news.mathworks.com comp.soft-sys.matlab:515157

"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <gm1kol$fd6$1@fred.mathworks.com>...
> "Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <gm0haa$jal$1@fred.mathworks.com>...
> > "Dave Brackett" <davebrackett@hotmail.com> wrote in message <gm0eee$imn$1@fred.mathworks.com>...
> > > Yes, by range I mean the difference between the smallest and largest elements. And yes repetitions are allowed. The sum of the elements must in this case equal 10, and each element must be an integer. 
> > > 
> > > The reason I am minimising the range is because a vector of elements e.g. [3,3,2,2] is preferred over [4,4,1,1]. For the first vector the range is 1, and the second the range is 3. 
> > > 
> > > How can I code up the finding of these elements for an arbitrary length vector and and arbitrary value that they must sum to, subject to the integer constraint? Thanks.
> > 
> >   Let n be the number of elements in the vector and s their sum.
> > 
> >  r = rem(s,n);
> >  q = (s-r)/n;
> >  v = fix(q+(r+sign(s)*(0:n-1))/n);
> > 
> > Then v is your desired vector.
> > 
> >   Note: this could be a little simpler if s were known to always be positive.
> > 
> > Roger Stafford
> 
>   I could just as well used the simpler one-liner:
> 
>  v = floor((s+(0:n-1))/n);
> 
> It works for all integers s, positive or negative, and all positive integers, n.
> 
> Roger Stafford

thanks a lot Roger, that works really well, and is a much simpler way than I was trying.