Path: news.mathworks.com!not-for-mail
From: "Tim Davis" <davis@cise.ufl.edu>
Newsgroups: comp.soft-sys.matlab
Subject: Re: multiplying diag matrix with a reg matrix
Date: Sun, 5 Apr 2009 13:08:01 +0000 (UTC)
Organization: University of Florida
Lines: 39
Message-ID: <graafh$268$1@fred.mathworks.com>
References: <gr8g5t$gti$1@fred.mathworks.com> <gr8hit$cto$1@fred.mathworks.com>
Reply-To: "Tim Davis" <davis@cise.ufl.edu>
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 1238936881 2248 172.30.248.37 (5 Apr 2009 13:08:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 5 Apr 2009 13:08:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 45902
Xref: news.mathworks.com comp.soft-sys.matlab:530443

"Matt Fig" <spamanon@yahoo.com> wrote in message <gr8hit$cto$1@fred.mathworks.com>...
> A = round(rand(1000)*10000);
> D = diag(randperm(1000));
> 
> There are several ways to do this.  Here are two shown in comparison.
> 
> 
> 
> 
> 
> N = 1000;
> A = round(rand(N)*N^2);
> D = diag(randperm(N));
> 
> tic
> H = D*A;
> toc
> 
> tic
> C = bsxfun(@times,A,D(1:N+1:end).');  % Or use diag(D)
> toc
> 
> tic
> E = sparse(D)*A;
> toc
> 
> all(H(:)==C(:)) 
> all(H(:)==E(:))

Except that creating a dense matrix D then doing sparse(D) is slow.  Better would be

d = randperm(N);
tic
E = sparse(1:n,1:n,d)*A;
toc

which never forms the dense D matrix, and is much faster than

E = sparse(D)*A;