revised affinity matrix code