2

I have the following

j = {{1, 2}, {3, 2}, {5, 4}, {1, 2}, {3, 2}}
k = {1, 2, 3, 4, 5}
t = SparseArray[j -> k, Max@j {1, 1}]

The above creates a 5x5 matrix which is

{{0, 1, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 2, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 3, 0}}

As you can see the first element {1, 2} is still $1$. It is not replaced by $4$. Similar thing happens to {3, 2} element in the t matrix.

What I want is the following: if there is a repeated element in j, then that corresponding element in t matrix should be the sum of the two j elements, such as {1, 2} -> 1 + 4, {3, 2} -> 2 + 5 etc. in the t matrix.

How can i do that?

MarcoB
  • 67,153
  • 18
  • 91
  • 189
no-one
  • 1,243
  • 9
  • 14

1 Answers1

0

This is the first thing I came up with:

singles = Thread[j -> k];
mostuniques = DeleteDuplicatesBy[SortBy[First]@singles, First];
duplicates = Complement[singles, mostuniques];
Plus @@ (SparseArray[#, Max@j]& /@ {mostuniques, duplicates});
Normal@%

(* Out: {{0, 5, 0, 0, 0}, 
         {0, 0, 0, 0, 0}, 
         {0, 7, 0, 0, 0}, 
         {0, 0, 0, 0, 0}, 
         {0, 0, 0, 3, 0}} *)
MarcoB
  • 67,153
  • 18
  • 91
  • 189