Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: compare two vectors
Date: Sun, 2 Nov 2008 08:14:02 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 30
Message-ID: <gejnga$3p9$1@fred.mathworks.com>
References: <geit6f$8ev$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 1225613642 3881 172.30.248.37 (2 Nov 2008 08:14:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 2 Nov 2008 08:14:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:498491


"ann au" <fannylyy@hkusua.hku.hk> wrote in message <geit6f$8ev$1@fred.mathworks.com>...
> Hi,
> 
> I have two vectors:
> 
> a=[1 1 1 1 1 2 2 3 4 5 6 7]'
> b = [1 1 2 2 5 6]'
> 
> I want to get the following result:
> r = [1 1 1 3 4 7]'
> 
> What code can I use?
> Thanks a lot!
> 
> Ann

  I assume that for each element present in 'a' in greater quantity than in 'b' you wish 'r' to contain as many copies of that element as this difference.  That is, in your example 'r' has three 1's presumably because 'a' contains three more 1's than does 'b'.

  If that is what you intend, try this:

 e = union(a,b); % List all unique elements of combined a and b
 n = max(histc(a,e)-histc(b,e),0); % How many of each e element
 p = accumarray(cumsum(n)+1,1); % Proceed to generate r
 p(1) = p(1)+1;
 r = e(cumsum(p(1:end-1)));

  The vector 'n' above contains the desired number of elements for 'r' of each of the corresponding elements of 'e'.  The remaining three lines are devoted to generating just such a vector 'r'.

Roger Stafford