M-M
M-M

Reputation: 901

Value Error on computing matrix elements sum

I am trying to write a function that adds all elements in a matrix. The special condition is if an element in the matrix is 0, we count the element below this 0 also 0. For example:

matrix = 

[[0, 1, 1, 2], 

[0, 5, 0, 0],

[2, 0, 3, 3]] 

Should return 9 because 1+1+2+5=9

Here is what I have for my code, I got this error, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Can someone please help?

import numpy as np
def matrixElementsSum(matrix):
    a=np.array([matrix])
    sumofcolumn=0
    sum=0
    for x in range(len(a)): # x in matrix row
        for y in range(len(a[0])): #y in matrix col
            if a[x][y]==0:
                a[x+1][y]==0 #set next row same column=0
            sumofcolumn+=a[x][y] #sumofcolumn is a column sum
    for x in sumofcolumn:
        sum+=x
    return sum

Upvotes: 1

Views: 860

Answers (6)

0Knowledge
0Knowledge

Reputation: 755

I know this is vary late...

def matrixElementsSum(matrix):
    sum = 0
    for r in range(len(matrix)):
        for c in range(len(matrix[r])):
            if (matrix[r][c] != 0):
                if (r==0):
                    sum += matrix[r][c]
                else:
                    if(matrix[r-1][c] !=0):
                        sum += matrix[r][c]
            else:
                if(r == len(matrix)-1):
                    continue
                else:
                    matrix[r+1][c] = 0
    return sum

Upvotes: 0

Elham Khan
Elham Khan

Reputation: 71

def matrixElementsSum(matrix):
  totalSum = 0
  for row in range(len(matrix)):
   for col in range (len(matrix[0])):
      if matrix[row][col] == 0 and row != len(matrix) -1:
        matrix[row+1][col] = 0
      else:
       totalSum = totalSum + matrix[row][col]
  return totalSum

Upvotes: 0

Aivar Paalberg
Aivar Paalberg

Reputation: 5139

It can be done with rows-to-columns and flat list where index is increased by 2 if value is 0:

def matrix_elements_sum(matrix):
    lst = sum(list(zip(*matrix)), ())    # rows-to-columns and to flat list
    total = 0
    i = 0
    while i < len(lst):
        if lst[i] != 0:
            total += lst[i]
            i += 1  
       else:
            i += 2
    return total

Upvotes: 0

Kiran Kumar Kotari
Kiran Kumar Kotari

Reputation: 1160

Find the woking code with inline comments where you got wrong.

import numpy as np


def matrixElementsSum(matrix):
    a = np.array(matrix)  # no need of appending in []
    my_sum = 0 #  sumofcolumn not required
    for x in range(len(a)):  # x in matrix row
        for y in range(len(a[x])):  # y in matrix col
            if a[x][y] == 0 and x < len(a)-1: #  handling last index
                a[x+1][y] = 0  # set next row same column=0
            my_sum += a[x][y]  # adding value to sum..
    #  no for loop required, you are not appending values to a list.
    #  it's an integer and it's declared outside of loops.
    return my_sum


matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
print(matrix)
print(matrixElementsSum(matrix))

Upvotes: 1

user3483203
user3483203

Reputation: 51155

You could rotate, flatten, and them use a simple comprehension:

import numpy as np

matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
matrix = np.rot90(matrix).flatten()
indices = set(np.where(matrix==0)[0]+1) # set of indices to the right of 0 fast lookup
final = sum(e for i,e in enumerate(matrix) if i not in indices)
print(final)

Output:

9

When you rotate and flatten, you are left with:

[2 0 3 1 0 3 1 5 0 0 0 2]

And if you notice, all the values that had 0 above them in your matrix, now have 0 to the left of them, and you can use the list comprehension to ignore these, and then find the sum of the result.

I'm sure there is a way to do this without the rotation, but I feel this way is much easier to visualize.

Upvotes: 2

JahKnows
JahKnows

Reputation: 2706

You can do this as follows

total = 0
zeros = []
for row in matrix:
    total += sum([val for ix, val in enumerate(row) if not ix in zeros])
    zeros = [ix for ix, i in enumerate(row) if i == 0]
total

Upvotes: 0

Related Questions