Path: news.mathworks.com!not-for-mail
From: "Sadik " <sadik.hava@gmail.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: vectorize a simple for loop?
Date: Fri, 11 Dec 2009 03:24:19 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 34
Message-ID: <hfse13$fm8$1@fred.mathworks.com>
References: <hfs6om$bv5$1@fred.mathworks.com>
Reply-To: "Sadik " <sadik.hava@gmail.com>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1260501859 16072 172.30.248.38 (11 Dec 2009 03:24:19 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 11 Dec 2009 03:24:19 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1666517
Xref: news.mathworks.com comp.soft-sys.matlab:591830

Hi Steve,

You can easily verify that the (m,n)th element of a matrix corresponds to that matrix's 

(n-1)*M+m th

element.

For example, if

A = [1 2 3 4 5;
       6 7 8 9 10;
       11 12 13 14 15;
       16 17 18 19 20;
       21 22 23 24 25];

then, A(3,2) = 12, which is equal to A(k) where k = (2-1)*size(A,1)+3.

We can use the same trick. In fact, you can see that the values in dum are all column indices. The first row is for the first row of Dij, the second is for the second and so on. So we can define:

dum2 = (dum - 1)*size(dum,1)+diag(1:size(dum,1))*ones(size(dum));

The first term in the sum is obvious: (n-1)*M. The second term does nothing but determines m in (n-1)*M+m. 

So the answer to your question is

dum = [1 3; 1 4; 2 4];
dum2 = (dum - 1)*size(dum,1)+diag(1:size(dum,1))*ones(size(dum));
Dij = zeros(size(dum,1),4);
Dij(dum2(:)) = 1;

gives what you are looking for.

Best.