Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to take common rows and columns from two matrices.
Date: Mon, 13 Jun 2011 20:30:25 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 59
Message-ID: <it5s11$il9$1@newscl01ah.mathworks.com>
References: <ist0dv$our$1@newscl01ah.mathworks.com> <ist5eq$9qr$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-00-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1307997025 19113 172.30.248.45 (13 Jun 2011 20:30:25 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 13 Jun 2011 20:30:25 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2910700
Xref: news.mathworks.com comp.soft-sys.matlab:731745

"Shawn Bonneau" <sbonneau@mathworks.com> wrote in message <ist5eq$9qr$1@newscl01ah.mathworks.com>...
> The code that follows uses logical indexing and the colon operator, and 
> assumes that matrix A is larger than B.
> 
> 
> A = [1 6 11 16
>     2 7 12 17
>     3 8 13 18
>     4 9 14 19
>     5 10 15 20];
> 
> B=[ 2 7
>     5 10];
> 
> for rowA = 1:size(A,1)     %loop through all rows in matrix A
> 
>     for rowB = 1:size(B,1)     %for each A row, loop through all B rows
>       rowAmatchesRowB(rowB)= (all(A(rowA,1:size(B,2))==B(rowB,:))); 
> %check if the elements in row A (up to the number in row B) match with all 
> those in row B
>     end
> 
>     AIndex(rowA)=any(rowAmatchesRowB);    %if row A matched any row in B, 
> set the index to true
> 
> end
> 
> C=A(AIndex,:)     %use logical indexing to get desired rows
> 
> 
> 
> "jewi " <enphy@hotmail.com> wrote in message 
> news:ist0dv$our$1@newscl01ah.mathworks.com...
> > Hello all,
> >
> > Could anyone help plz;
> > I have two matrices with different number of columns and rows.
> > e.g, A =
> >     1     6    11    16
> >     2     7    12    17
> >     3     8    13    18
> >     4     9    14    19
> >     5    10    15    20
> > and
> >     B=
> >      2     7
> >      5     10
> >
> > I want to select rows from A which are common with B, but i want to take 
> > the whole row from A with all columns.
> > For example in the above case my desired result would be;
> >   C=
> >   2 7 12 17
> >   5 10 15 20
> >
> > Thanks,
> > Jewi. 

Thank you very much shawn; it worked well.