![]() Volume 10, Issue 2 Articles In and Out Trott's Corner Beyond Sudoku New Products New Publications Calendar News Bulletins New Resources Classifieds Download This Issue Editorial Policy Staff and Contributors Submissions Subscriptions Advertising Back Issues Contact Information |
In and Out
Cluster AnalysisQ: 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
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 © 2006 Wolfram Media, Inc. All rights reserved. |