5
$\begingroup$

I am trying to sum over specific indices in a matrix.

For example, if I have the matrix

a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}}

i need to sum the index {2, 1} and {4, 3} , i.e 4 + 9 = 13 automatically.

I try the code

Sum[a[[ii]][[jj]], {ii, 2, 4, 2}, {jj, 1, 4 , 2}]

and this is equals to 20. (WTF) (i think this shows the result of 4+6+1+9) Why?

In a general form I need to compute the sum of indices {2, 1}, {4, 3}, {6, 5}, {8, 7}, {10, 9}, {12, 11}, {14,13}, {16,15} for a 16x16 square matrix.

Thanks for the help

Regards

$\endgroup$

7 Answers 7

11
$\begingroup$
a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};
positions = {{2, 1}, {4, 3}};
Total@Extract[a, positions]
$\endgroup$
1
  • $\begingroup$ thanks bro. your answer was useful $\endgroup$
    – 0xTochi
    Commented Oct 13, 2018 at 20:21
8
$\begingroup$

To see why it doesn't work as you expected, look at the indices that you generated.

Table[{ii, jj}, {ii, 2, 4, 2}, {jj, 1, 4, 2}]

(* {{{2, 1}, {2, 3}}, {{4, 1}, {4, 3}}} *)

You generated four indices so the sum was over four entries. Use

a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};

Sum[a[[Sequence @@ i]], {i, {{2, 1}, {4, 3}}}]

(* 13 *)
$\endgroup$
1
  • $\begingroup$ thanks, now i can understand my problem $\endgroup$
    – 0xTochi
    Commented Oct 13, 2018 at 20:22
8
$\begingroup$

I would have used Extract if Alan had not posted it first.

So, here is a way to use Sum:

Sum[a[[## & @@ i]], {i, {{2, 1}, {4, 3}}}]

13

But that is also posted a minute earlier by Bob Hanlon.

That leaves

☺ = {♯, ♯♯} \[Function] +## & @@ (♯[[##]] & @@@ ♯♯);
☺[a, {{2, 1}, {4, 3}}]

13

and

☺☺ = +## & @@ (♯ \[Function] #[[## & @@ ♯]]) /@ #2 &;
☺☺[a, {{2, 1}, {4, 3}}]

13

$\endgroup$
0
6
$\begingroup$
a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};
a[[##]] & @@@ Thread@Range[{2, 1}, {4, 3}, 2] // Total

13

Where you would replace {4,3} with {16,15} in Range for the bigger matrix.

$\endgroup$
5
$\begingroup$
a[[Sequence @@ #]] & /@ {{2, 1}, {4, 3}} // Total

13

$\endgroup$
3
$\begingroup$

Just for giggles, and using your $16\times 16$ example:

Tr[IdentityMatrix[16][[Range[2 ,16, 2]]].
 Array[C, {16, 16}].
 Transpose[IdentityMatrix[16][[Range[1, 15, 2]]]]]
$\endgroup$
2
  • $\begingroup$ (I am still stuck on gedanken Mathematica, but I believe that ought to work.) $\endgroup$ Commented Oct 13, 2018 at 4:40
  • $\begingroup$ wow. is beautiful $\endgroup$
    – 0xTochi
    Commented Oct 13, 2018 at 20:27
2
$\begingroup$
list = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};

p = {{2, 1}, {4, 3}};

Using MapApply (new in 13.1)

Total @ MapApply[list[[##]]&] @ p

13

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.