Path: news.mathworks.com!not-for-mail
From: "Kevin Lin" <klin@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to insert/delete rows in a matrix without copy the rest of matrix
Date: Sun, 18 Nov 2007 00:14:41 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 82
Message-ID: <fho05h$3be$1@fred.mathworks.com>
References: <f87kg3$9ri$1@fred.mathworks.com> <f87ooi$rma$1@fred.mathworks.com> <f87t7h$mje$1@fred.mathworks.com> <f87uil$ggh$1@fred.mathworks.com>
Reply-To: "Kevin Lin" <klin@mathworks.com>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1195344881 3438 172.30.248.35 (18 Nov 2007 00:14:41 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 18 Nov 2007 00:14:41 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187478
Xref: news.mathworks.com comp.soft-sys.matlab:438144



If I want to delete arbitrary m rows (for simplicity, say
m=2 and 3) in a matrix, what can I do? Thanks if any of you
can help.

"Tim Davis" <davis@cise.ufl.edu> wrote in message
<f87uil$ggh$1@fred.mathworks.com>...
> "Chenyang " <john.doe.nospam@mathworks.com> wrote in
message <f87t7h$mje$1@fred.mathworks.com>...
> > Thank you, but this is not a "true" solution.  The codes
are just for illustration of the problem.  What if you want
to delete/add the 99th row?  
> > 
> > The problem lies Matlab copying whole matrix while
actually only a very small portion of the matrix being modified.
> > I guess to really solve this problem we have to find a
data-structure that allows a matrix to span multiple memory
segments and are somehow linked together by indexing pointers. 
> >
> 
> 
> MATLAB stores a dense matrix in an m-by-n array, in column
major form, without pointers.  Using pointers would cause a
dreadful slowdown in any matrix computations other than
> 
> a (:,1) = [ ] ;
> 
> which is why no pointers are used (the BLAS do not use
pointers).
> 
> So the problem is intrinsically difficult.
> 
> Your best solution would be to avoid the need to delete
rows/columns at all.  Can you set the row or column to
delete to zero, for example?
> 
> Another alternative would be to keep a list of rows and
columns that have not been "deleted", but not to change a
itself.  Try this:
> 
> a = rand (5000) ;
> 
> delrow = 99 ;
> 
> tic
> b = [a(1:delrow-1,:) ; a(delrow+1:end,:)] ;
> toc
> 
> tic
> a (delrow,:) = [ ];
> toc
> 
> [m n] = size (a)
> p = logical (ones (m, 1)) ;
> q = logical (ones (1, n)) ;
> nrows = m ;
> ncols = n ;
> 
> % to delete a row in a:
> p (delrow) = 0 ;
> nrows = nrows - 1 ;
> 
> % to delete a colum in a:
> q (101) = 0 ;
> ncols = ncols - 1 ;
> 
> tic
> b = a(p,q) ;
> toc
> 
> % try using a(p,q) explicitly:
> x = rand (ncols,1) ;
> tic
> y = a(p,q) * x ;
> toc
> 
> tic
> y = b*x ;
> toc
> 
> 
> The logical indexing is a little faster.