Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Efficient way to create adjacency matrix in Mata


From   Maarten Buis <maartenlbuis@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Efficient way to create adjacency matrix in Mata
Date   Thu, 30 Jun 2011 09:50:54 +0200

On Wed, Jun 29, 2011 at 10:01 PM, Benjamin Allaire wrote:
> Question: what is the most efficient way to create an adjacency matrix in mata,
> given a unique identifier ("id") and a club id ("club_id") for folks in the same club.
>
> So the data looks like this:
>
> id    club_id
> 1       1
> 2       1
> 3       2
> 4       2
> 5       2
>
> Is there a clever way to do it without looping over the people?

In this datastructure persons can only be members of one club. If this
is also true in your data, then the adjacency matrix is a block
diagonal matrix, which you could fill by looping over clubs rather
than observations.

*------------ begin example ----------------
// type in some data
drop _all
input ///
id    club_id
1       1
2       1
3       2
4       2
5       2
6       3
7       3
end

// sort first on club_id and than on id
sort club_id id

// identify first observation per club
by club_id (id) : gen byte first = _n == 1

// store number of club members
by club_id (id) : gen n = _N if first == 1

// rolling count of number of observations
gen rolln = sum(n)

mata
// get one row per club
st_view(club=., ., "club_id n rolln", "first")

// total number of observations
N = colsum(club[.,2])

// create an adjacency matrix with all 0s
adj = J(N, N, 0)

// fill in first club
n = club[1, 2]
lcorner = 1
rcorner = club[1, 3]
adj[|lcorner, lcorner \ rcorner, rcorner|] = J(n,n,1)

// fill in remaining clubs
for (i = 2 ; i <= rows(club); i++) {
	n = club[i, 2]
	lcorner = club[i-1, 3] + 1
	rcorner = club[i, 3]
	adj[|lcorner, lcorner \ rcorner, rcorner|] = J(n,n,1)
}

// see the matrix
adj
end
*----------------------------- end example ------------------------
(For more on examples I sent to the Statalist see:
http://www.maartenbuis.nl/example_faq )

Hope this helps,
Maarten

--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany


http://www.maartenbuis.nl
--------------------------

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index