Sum of diagonal elements in a matrix

后端 未结 11 2474
有刺的猬
有刺的猬 2021-02-12 11:35

I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happen

相关标签:
11条回答
  • 2021-02-12 12:24

    O(n) time solution to find the diagonal difference of given multidimensional array.

    def diagonalDifference(arr):
            # arr[0][0], arr[1][1], arr[2][2]
            # arr[0][2], arr[1][1], arr[2][0]
            sumOfDiagonalFromLeft = 0
            sumOfDiagonalFromRight = 0
            pointIndexFromLeft = 0
            pointIndexFromLast = len(arr)-1
            for i in range(len(arr)):
                sumOfDiagonalFromLeft += arr[i][pointIndexFromLeft]
                # print(arr[i][pointIndexFromLeft])
                pointIndexFromLeft += 1
            
            for i in range(len(arr)):
                sumOfDiagonalFromRight += arr[i][pointIndexFromLast]
                # print(arr[i][pointIndexFromLast])
                if pointIndexFromLast < 0:
                    break
                else:
                    pointIndexFromLast -= 1
        
            diagonalDifference = abs(sumOfDiagonalFromLeft - sumOfDiagonalFromRight)
            return diagonalDifference
        
    arr = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
    print(diagonalDifference(arr))
    
    0 讨论(0)
  • 2021-02-12 12:25

    getting total and diagonal sum from a squared matrix

    squared_matrix = [[2,3,4],[4,3,3],[3,3,4]]
    s, ds = get_sum(squared_matrix)
    
    def get_sum(diag_mat):
        n = len(diag_mat)
        total = sum([diag_mat[i][j] for i in range(n) for j in range(j)]
        d_sum = sum([diag_mat[i][j] if i==j else 0 for i in range(n) for j in range(j)]
       return d_sum, total
    
    0 讨论(0)
  • 2021-02-12 12:25
    def sum_diagnol():
        import random
        sum=0
        r1=int(input("row"))
        c1=int(input("col"))
        a=[[random.random()for col in range(c1)]for row in range(r1)]
        print("enter elements")
        for i in range(r1):
            for j in range(c1):
                a[i][j]=int(input("enter elements"))
        r2=int(input("row"))
        c2=int(input("col"))
        b=[[random.random()for col in range(c2)]for row in range(r2)]
        print("enter elements")
        for i in range(r2):
            for j in range(c2):
                b[i][j]=int(input("enter elements"))
        c=[[random.random()for col in range(c2)]for row in range(r1)]
        if(c1==r2):
            for i in range(r1):
                for j in range(c2):
                    c[i][j]=0
                    for k in range(c2):
                        c[i][j]=a[j][k]*b[k][j]
        else:
            print("multiplication not possible")
        for i in range(r1):
            for j in range(c2):
                print(c[i][j],end=" ")
            print()
    sum_diagnol()
    
    0 讨论(0)
  • 2021-02-12 12:25

    I found a simple algorithm to accomplish this task.

    1. Store the square matrix in a single one dimensional array.

    2. Let 'n' be the order of square matrix.

    3. There are two diagonals , one that starts from the leftmost element in top row and another that starts from nth element of the top row.

    4. To get the indexes of numbers on the diagonal that starts from left most element in top row ,from the array containing all the numbers in the matrix; just add (n+1) recursively starting from index 1. That is, indexes of elements in left to right diagonal in the array are, 1, 1+(n+1) , (n+2)+(n+1) , (2n+3)+(n+1) till the last index of array.

    5. To get the indexes of another diagonal's numbers from the array containing all the numbers in the matrix ; just add (n-1) recursively to the indexes starting from index equals to the 'n', which is the order of the square matrix. That is, indexes of elements in right to left diagonal in the array are, n, n+(n-1), (2n-1)+(n-1) and so on till the index equals to 'length of the array - (n-1)'.

    6. If the order is odd then subtract the middle number in the array from the final sum.

    The example 'c++' code is as follows:

     #include<iostream>
     using namespace std;
    
    int sumOfDiagonalNumbersInSquareMatrix(int numberArray[],int order){
    int sumOfLeftToRightDiagonal = 0;
    int sumOfRightToLeftDiagonal = 0;
    int length = order*order;
    for(int i=0; i<length;i+=(order+1)){
        //cout<<numberArray[i]<<"\t";
        sumOfLeftToRightDiagonal = sumOfLeftToRightDiagonal + numberArray[i];
    
    }
    for(int i=(order-1);i<=length-order;i+=(order-1)){
        //cout<<numberArray[i]<<"\t";
        sumOfRightToLeftDiagonal = sumOfRightToLeftDiagonal + numberArray[i];
    }
    if(order % 2 != 0){
        return (sumOfLeftToRightDiagonal + sumOfRightToLeftDiagonal) - numberArray[(length/2)];
    }
    return (sumOfLeftToRightDiagonal + sumOfRightToLeftDiagonal);
    }
    
     int main(){
     int nums[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
     cout<<sumOfDiagonalNumbersInSquareMatrix(nums,4);
     return 0;
     }
    

    You can run it here: http://cpp.sh/6cmdp

    0 讨论(0)
  • 2021-02-12 12:31

    '''

    a = [[],[],[]] #your matrix
    s = 0
    for i in range(len(a)):
        for j in range(len(a[0])):
               if i == j:
                   s += a[i][j]
    print('sum ='s)
    

    ''' here is a simple approach. Thanks

    0 讨论(0)
提交回复
热议问题