Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to insert/delete rows in a matrix without copy the rest of matrix
Date: Mon, 21 Jul 2008 23:04:05 +0000 (UTC)
Organization: CBS
Lines: 52
Message-ID: <g634l5$qe3$1@fred.mathworks.com>
References: <f87kg3$9ri$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 1216681445 27075 172.30.248.37 (21 Jul 2008 23:04:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 21 Jul 2008 23:04:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1446277
Xref: news.mathworks.com comp.soft-sys.matlab:480795



"Chenyang " <john.doe.nospam@mathworks.com> wrote in message
<f87kg3$9ri$1@fred.mathworks.com>...
> Matlab is very slow add/delete a row in a matrix.
> It always trying to copy the whole matrix
> e.g., 
> 
> a = rand(5000);
> tic
> a(:,1) = [];
> toc
> tic
> a = [a(:,1),a];
> toc
> Elapsed time is 0.447241 seconds.
> Elapsed time is 0.556416 seconds.
> 
> I need to insert/delete a row into a large matrix.
> How to make it fast?
> 


One fast way of doing this is to first fill the rows with
zeros, and then delete them using the 'any' function as follows:

tic
x = rand(50000,10);
for i = 50000:-100:1
    x(i,:) = [];
end
toc

>>Elapsed time is 4.813505 seconds.

tic
x = rand(50000,10);
for i = 50000:-100:1
    x(i,:) = 0;
end
x(~any(x,2),:) = [];
toc

>>Elapsed time is 0.058070 seconds.

I cannot give a technical explanation for why the second
method is so much faster, but I would like to hear one if
anyone knows... I guess it has to do with the logical
indexing. My own problem was to delete very many irregularly
spaced rows from a matrix of app. the dimensions above, and
this method does the job very quickly.