1

I am trying to write a function that will find a sum of all diagonal elements of matrix. I don't know how to do it correctly. This is how I tried do do it.

 matrix[n_, {rov_, column_}] := RandomInteger[n, {rov, column}]
matrix[10, {5, 5}]
For[sum = 0; i = 0, i < rov, i++;
 For[j = 0, j < column, j ++;
  If[i == j, sum = sum + matrix[10, {5, 5}]
   ]
  ]
 ]

First I have written a function that generates matrix. And than I tried to write the function that will find the sum of diagonal elements.

David G. Stork
  • 41,180
  • 3
  • 34
  • 96
Cro Simpson2.0
  • 453
  • 3
  • 10

2 Answers2

2

Let's have an answer so this question can be ticked off ...

To calculate the sum of the elements on the main diagonal of a matrix use the intrinsic function Tr. In your case something like

Tr[matrix[10, {5, 5}]]

Before you use For, read the material @george2079 pointed you at. If you are a beginner with Mathematica check out the documentation for Tr and follow the links to other related functions, do some discovery for yourself of what is already built in to the system.

In the code you've shown us you've made some slips in using ; and , correctly in the If and For calls. For someone whose mind has been over-influenced by C and its ilk the two punctuation marks might, on studying the Mathematica documentation, seem to be used the wrong way round.

As @george2079 has also pointed out your matrix is a function which, each time it is called, generates a new random matrix. It doesn't make any sense to call it at each execution of the If statement inside the loop nest. Perhaps you should write

mat1 = matrix[10, {5, 5}]

and then execute

Tr[mat1]
High Performance Mark
  • 1,534
  • 1
  • 10
  • 17
1
(matrix = Array[a, {5, 5}]) // MatrixForm

enter image description here

Tr[matrix]

(* a[1, 1] + a[2, 2] + a[3, 3] + a[4, 4] + a[5, 5] *)

Total@Diagonal@matrix

(* a[1, 1] + a[2, 2] + a[3, 3] + a[4, 4] + a[5, 5] *)

Total[matrix[[#, #]] & /@ Range[5]]

(* a[1, 1] + a[2, 2] + a[3, 3] + a[4, 4] + a[5, 5] *)

Total@Table[matrix[[i, i]], {i, 5}]

(* a[1, 1] + a[2, 2] + a[3, 3] + a[4, 4] + a[5, 5] *)

For[sum = 0; i = 1, i < 6, i++, sum += matrix[[i, i]]]; sum

(* a[1, 1] + a[2, 2] + a[3, 3] + a[4, 4] + a[5, 5] *)
Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198