0
def addM(a, b):
    res = []
    for i in range(len(a)):
        row = []
        for j in range(len(a[0])):
            row.append(a[i][j]+b[i][j])
        res.append(row)
    return res

I found this code here which was made by @Petar Ivanov, this code adds two matrices, i really don't understand the 3rd line, why does he use len(a) and the 5th line, why does he use len(a[0]). In the 6th line, also why is it a[i][j] +b[i][j]?

1 Answer 1

2

The matrix here is a list of lists, for example a 2x2 matrix will look like: a=[[0,0],[0,0]]. Then it is easy to see:

  1. len(a) - number of rows.
  2. len(a[0]) - number of columns (since this is a matrix, the length of a[0] is the same as length of any a[i]).
  3. This way, i is the number of row, j is the number of column and a[i][j]+b[i][j] is simply adding up the elements of two matrices which are placed in the same locations in the matrices.

For all this to work, a and b should be of the same shapes (so, numbers of rows and columns would match).

Sign up to request clarification or add additional context in comments.

2 Comments

if they are not the same (matrices) will i get an error or do i have to modify the code in order to return none? if len(a) != len(b): return None
@user2971015 It would certainly be a good idea to handle len(a)!=len(b) or len(a[0])!=len(b[0]) to be sure the input is right. You also need to check if all the row lengths for each of a and b are the same, otherwise they won't be considered matrices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.