The Mathematica Journal
Volume 10, Issue 2

Search

In This Issue
Articles
In and Out
Trott's Corner
Beyond Sudoku
New Products
New Publications
Calendar
News Bulletins
New Resources
Classifieds

Download This Issue 

About the Journal
Editorial Policy
Staff and Contributors
Submissions
Subscriptions
Advertising
Back Issues
Contact Information

In and Out
Edited by Paul Abbott

Cluster Analysis

Q: For an arbitrary matrix of non-negative integers, how can I obtain the sum of those matrix elements that are surrounded by zeros? As a concrete example, for the following matrix an output of is required.

The order in which the groups surrounded by zero is summed does not matter.

A: Carl Woll (carlw@wolfram.com) answers: First, use SparseArray to get the positions of non-zero elements.

Next, define a distance function yielding 0 for identical elements, 1 for adjacent elements, and a big number, say 10, for nonadjacent elements.

Then, load the Statistics`ClusterAnalysis` package and use FindClusters with the Agglomerate method.

Finally, total the cluster values.

Here is a function to do all the steps.

Check that ClusterSums works on mat.

As a bonus, this approach can be extended to handle higher dimensional arrays.



     
About Mathematica | Download Mathematica Player 
© Wolfram Media, Inc. All rights reserved.