6 kyu

Matrix Trace

74 of 898chipit24

Description:

Calculate the trace of a square matrix. A square matrix has n rows and n columns, where n is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or nil/None if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below).

The trace of an n-by-n square matrix A is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of A.

A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on.

For example, the following code...

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

represents the matrix

|1 2 3|
|4 5 6|
|7 8 9|

which has a trace of 1 + 5 + 9 = 15.

You can read more about the trace of a matrix at these sources:

Note: The Matrix class is disabled.

Linear Algebra
Mathematics
Matrix
Algorithms

Similar Kata:

More By Author:

Check out these other kata created by chipit24

Stats:

CreatedApr 5, 2015
PublishedApr 5, 2015
Warriors Trained1238
Total Skips20
Total Code Submissions3053
Total Times Completed898
Ruby Completions74
Python Completions811
Haskell Completions35
Total Stars20
% of votes with a positive feedback rating93% of 168
Total "Very Satisfied" Votes146
Total "Somewhat Satisfied" Votes21
Total "Not Satisfied" Votes1
Total Rank Assessments7
Average Assessed Rank
6 kyu
Highest Assessed Rank
6 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • chipit24 Avatar
  • Unnamed Avatar
  • anter69 Avatar
  • ZED.CWT Avatar
  • cliffstamp Avatar
Ad