Multiplication of matrix rows with each other and with another list

Viewed 48

I am trying to multiply a matrix containing voxel sizes with a list of single numbers (containing the amount of voxels). Something like this:

a = [(1, 2, 3), (2, 3, 4)]
b = [5, 6]

hocuspocus = [1 * 2 * 3 * 5, 2 * 3 * 4 * 6] = [30, 144]

Because I need to provide the voxels in cubic millimeters, I need to multiply the content of each matrix row with each other and then with list b. Haven't yet figured out how to do that in python. Does anyone have any suggestions? Thanks.

1 Answers

You could go for something like this, which uses the prod() function to multiply all numbers in a row and reduce them in a single value, and then the for statement of this list comprehension iterates the two lists a and b and multiplies them element-wise.

Python 3.7 or older

from functools import reduce  # Required in Python 3.
from operator import mul

def prod(iterable): # This function multiplies all numbers of a row.
    return reduce(mul, iterable, 1)
    
a = [(1, 2, 3), (2, 3, 4)]
b = [5, 6]
    
out = [prod(row) * elem for row, elem in zip(a, b)]

print(out)

Python 3.8+

Alternatively you could use the native prod() function in the math module.

from math import prod
    
a = [(1, 2, 3), (2, 3, 4)]
b = [5, 6]
    
out = [prod(row) * elem for row, elem in zip(a, b)]

print(out)

Output:

[30, 144]
Related