tags:

views:

94

answers:

2

english:

hello all, need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,

thanks for any response

español:

hola a todos, necesito definir una funcion que permita dividir termino a termino de matrices o en el peor de los casos, entre arreglos de listas de tal forma que obtenga el resultado en una tercera matriz,

gracias por cualquier respuesta

+4  A: 

Unless I'm misunderstanding, this is where numpy can be put to good use:

>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = array([[0.5] * 3, [0.5] * 3, [0.5] * 3])
>>> a / b
array([[  2.,   4.,   6.],
       [  8.,  10.,  12.],
       [ 14.,  16.,  18.]])

This works for multiplication too. And indeed, as noted by Mark, scalar division (and multiplication) is also possible:

>>> a / 10.0
array([[ 0.1,  0.2,  0.3],
       [ 0.4,  0.5,  0.6],
       [ 0.7,  0.8,  0.9]])
>>> a * 10
array([[10, 20, 30],
       [40, 50, 60],
       [70, 80, 90]])


Edit: to be complete, for lists of lists you could do the following:

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b = [[0.5] * 3, [0.5] * 3, [0.5] * 3]
>>> def mat_div(a, b): 
...     return [[n / d for n, d in zip(ra, rb)] for ra, rb in zip(a, b)] 
... 
>>> mat_div(a, b)
[[2.0, 4.0, 6.0], [8.0, 10.0, 12.0], [14.0, 16.0, 18.0]]
Stephan202
and if you have b same dimensions as a - e.g. b =a*10 you can also do b/a etc. I think he matrix combination is what the OP is asking
Mark
A: 

hello, thanks for response exelente solution

ricardo
Hi Ricardo, next time please leave a comment below the answer (just like this one). Stackoverflow works slightly different from other forums, in that it is actually not a forum: answers are reserved for... answers. Not general replies. Welcome at Stackoverflow!
Stephan202