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$

migrated from stats.stackexchange.com Oct 12 '18 at 21:48

This question came from our site for people interested in statistics, machine learning, data analysis, data mining, and data visualization.

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$
6
$\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$
  • $\begingroup$ thanks, now i can understand my problem $\endgroup$ – Santiago Marín Agudelo Oct 13 '18 at 20:22
5
$\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$
5
$\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$
3
$\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$
  • $\begingroup$ (I am still stuck on gedanken Mathematica, but I believe that ought to work.) $\endgroup$ – J. M. is away Oct 13 '18 at 4:40
  • $\begingroup$ wow. is beautiful $\endgroup$ – Santiago Marín Agudelo Oct 13 '18 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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