Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: construct diagonal block matrix
Date: Thu, 20 Aug 2009 21:17:23 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 72
Message-ID: <h6keh2$3fn$1@fred.mathworks.com>
References: <h0uj19$i02$1@fred.mathworks.com> <h6kcbr$c3k$1@fred.mathworks.com> <h6kcvo$mkl$1@fred.mathworks.com>
Reply-To: <HIDDEN>
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 1250803043 3575 172.30.248.35 (20 Aug 2009 21:17:23 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 20 Aug 2009 21:17:23 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1941167
Xref: news.mathworks.com comp.soft-sys.matlab:564906


"Matt " <xys@whatever.com> wrote in message <h6kcvo$mkl$1@fred.mathworks.com>...
> "Matt " <xys@whatever.com> wrote in message <h6kcbr$c3k$1@fred.mathworks.com>...
> > Here's a solution that meets the stated requirements, but I don't know if it saves anything. It uses kron, which is generally a slow operation
> 
> Actually, it does seem to save something. I did the following timing test on a larger data set. Note that my proposed solution constructs the final matrix B in sparse form, which saves some memory allocation ops. Conversely, blkdiag only returns its output in full form. However even when converting to full in method 1, I still find it to be considerably faster.
> 
> 
> A=rand(1000,2);
> 
> %method 1
> tic
> [m,n]=size(A);
> map=logical(kron(speye(m),ones(1,n)));
> [M,N]=size(map);
> 
> B=spalloc(M,N,numel(A));
> At=A.';
> B(map)=At(:);
> 
> %B=full(B);
> 
> toc
> %Elapsed time is 0.004230 seconds.
> 
> %Using blkdiag
> tic
>  C=num2cell(A,2);
>  BB=blkdiag(C{:});
> 
> toc
> %Elapsed time is 0.050917 seconds.

Matt - You're right, I included my solution in the test code:

clc;

A=rand(1000,2);

%method 1
tic
[m,n]=size(A);
map=logical(kron(speye(m),ones(1,n)));
[M,N]=size(map);

B=spalloc(M,N,numel(A));
At=A.';
B(map)=At(:);

B1=full(B);

toc
%Elapsed time is 0.017191 seconds.

%Using blkdiag
tic
 C=num2cell(A,2);
 B2=blkdiag(C{:});

toc
%Elapsed time is 0.035645 seconds.

% Using diag
tic
[m,n]=size(A);
A = [diag(A(:,1)) diag(A(:,2))];
B3 = A(:,reshape(reshape(1:m*n,m,n)',1,m*n));
toc
%Elapsed time is 0.063309 seconds.

All three methods give the same result, but Matt's method 1 is quickest.

Danny