Python Forum
Using map and lambda in a matrix
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using map and lambda in a matrix
#1
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.
Reply
#2
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]
>>>
Reply
#3
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))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Check if two matrix are equal and of not add the matrix to the list quest 3 778 Jul-10-2023, 02:41 AM
Last Post: deanhystad
  How to multiply a matrix with herself, until the zero matrix results peanutbutterandjelly 3 3,304 May-03-2021, 06:30 AM
Last Post: Gribouillis
  matrix from matrix python numpy array shei7141 1 3,643 Jan-16-2017, 06:10 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020