Calculates the sum of the principal diagonal of a square matrix - Java java.lang

Java examples for java.lang:Math Matrix

Description

Calculates the sum of the principal diagonal of a square matrix

Demo Code


//package com.java2s;

public class Main {
    /** //from   w  w w .  jav  a2s. com
     * Calculates the sum of the principal diagonal of a square matrix
     * @param matrix Matrix whose diagonal sum is to be calculated
     * @return Double containing the sum of the diagonal elements
     */
    public static <T> double getDiagonalSum(T[][] matrix) {

        double sum = 0.0;

        for (int i = 0; i < matrix.length; i++) {

            sum = sum + (Double) matrix[i][i];
        }

        return sum;
    }
}

Related Tutorials