MathGroup Archive 2013

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Sparse Array Question

  • To: mathgroup at
  • Subject: [mg130582] Re: Sparse Array Question
  • From: Bill Rowe <readnews at>
  • Date: Wed, 24 Apr 2013 06:58:47 -0400 (EDT)
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:

On 4/23/13 at 12:04 AM, chris.arthur1 at (christopher arthur)

>I have a list of rules for defining a SparseArray.  The list has
>some coordinates repeated with different values.  If a coordinate
>appears in the list more than once, I want to sum up the values, and
>then have a SparseArray

>i.e., if my list were myList={{1,1}->1,{2,1}->2,{1,1}->3} then my
>SparseArray should have {1,1}->4.  I've tried using ReplacePart on
>an array to say myArray=ReplacePart[myArray,...] but this seems
>horribly inefficient as a way to change values in an array.

>I'm using Mathematica 5.2

For your version this can be done as:

In[3]:= (#[[1, 1]] -> Total[#[[All, 2]]]) & /@
  Split[Sort[myList], SameQ[#1[[1]], #2[[1]]] &]

Out[3]= {{1,1}->4,{2,1}->2}

for version 7 and later this can be simplified to:

In[4]:= (#[[1, 1]] -> Total[#[[All, 2]]]) & /@ GatherBy[myList, First]

Out[4]= {{1,1}->4,{2,1}->2}

  • Prev by Date: Generalised Hough Transformation
  • Next by Date: Re: Sparse Array Question
  • Previous by thread: Re: Sparse Array Question
  • Next by thread: Re: Sparse Array Question