Python Forum

Full Version: Using map and lambda in a matrix
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi! I'm new to programming and I'm racking my brain to try to find an sum the diagonal of a matrix using map and lambda.

the matrix:

[inline]

matrix = [
[3],
[11,2,4],
[4,5,6],
[10,8,-12]

]
[/inline]

my code so far:

diagonal_r = list(map(lambda i: sum(i[0],i[1][1]), matrix ))

my idea was to use the same logic of sum function.

diagonal_r = sum(matrix[0],matrix[1][1],matrix[2][2],matrix[3][2])

but it does not work.
using numpy:
>>> import numpy as np
>>> matrix = np.asarray([[11,2,4],[4,5,6],[10,8,-12]])
>>> print(f'Sum of diagonal: {np.trace(matrix1)}')
Sum of diagonal: 4
>>> print(f'Elements of diagonal: {np.diagonal(matrix1)}')
Elements of diagonal: [ 11   5 -12]
>>>
matrix = [
    [3],
    [11,2,4],
    [4,5,6],
    [10,8,-12]
]
Do you think your matrix is right? You can calculate only the diagonal, if the dimension is x by x.
Also the first row has only one value. If you want to use numpy for example, this matrix you have posted is not possible.

Here an example with a 3 by 3 matrix:

matrix = [
    [11,2,4],
    [4,5,6],
    [10,8,-12]
]

diagonal = sum(matrix[i][i] for i in range(3))
Thank you Guys! The 3 was not part of the matrix. Was the number of inputs. Back to math class! :(

Larz60+ I thought about using numpy, but i want to learn the buitins functions first. Thank you!! DeaD_EyE your code is Very nice! Thanks!