Path: news.mathworks.com!not-for-mail
From: "Tim Davis" <davis@cise.ufl.edu>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to insert/delete rows in a matrix without copy the rest of matrix
Date: Wed, 25 Jul 2007 16:43:01 +0000 (UTC)
Organization: University of Florida
Lines: 62
Message-ID: <f87uil$ggh$1@fred.mathworks.com>
References: <f87kg3$9ri$1@fred.mathworks.com> <f87ooi$rma$1@fred.mathworks.com> <f87t7h$mje$1@fred.mathworks.com>
Reply-To: "Tim Davis" <davis@cise.ufl.edu>
NNTP-Posting-Host: webapp-00-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1185381781 16913 172.30.248.35 (25 Jul 2007 16:43:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 25 Jul 2007 16:43:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 45902
Xref: news.mathworks.com comp.soft-sys.matlab:421034



"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.