Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to do vectorize this simple code?
Date: Fri, 14 Nov 2008 23:43:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 46
Message-ID: <gfl2e5$24p$1@fred.mathworks.com>
References: <gfkstu$1id$1@fred.mathworks.com> <gfktep$9al$1@fred.mathworks.com> <gfkuen$m7v$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 1226706181 2201 172.30.248.35 (14 Nov 2008 23:43:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 14 Nov 2008 23:43:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1601482
Xref: news.mathworks.com comp.soft-sys.matlab:500928


"John D'Errico" <woodchips@rochester.rr.com> wrote in message <gfkuen$m7v$1@fred.mathworks.com>...
> "Scott " <crazyivan84__remove__@hotmail.com> wrote in message <gfktep$9al$1@fred.mathworks.com>...
> > If I understand you correctly, all you need is the diagonal. I believe this is the simplest way (at least that I'm aware of).
> > 
> > y(i)=diag(my_matrix(row(i),col(i)));
> 
> This is an extremely inefficient way to do it of course.
> 
> John

Actually, I've always found sub2ind to be quite slow.
Consider:

rows=randint(5,100000,[1,10]);
cols=randint(5,100000,[1,10]);
testMat=magic(10);

%Sub2ind
tic
resultsInd=zeros(100000,5);
for i=1:100000
    index=sub2ind(size(testMat),rows(:,i),cols(:,i));
    resultsInd(i,:)=testMat(index);
end
toc

%Diag
tic
resultsDiag=zeros(100000,5);
for i=1:100000
    resultsDiag(i,:)=diag(testMat(rows(:,i),cols(:,i)));
end
toc

isequal(resultsInd,resultsDiag)


With the result:
Elapsed time is 6.405682 seconds. (sub2ind)
Elapsed time is 0.293780 seconds. (diag)

ans =

     1